How to create a reactive label within an input in ReactJS with Styled-Components

Nadine Thery
urbanData Analytics
2 min readJul 15, 2021

--

Let’s check how to create a label within an input that changes according to the content and vice-versa.

For this article, I will be taking the basic CSS component we made in the previous post of this series: How to create an input with an inner label in ReactJs and Styled-Components

While in the previous post you could easily go with a simple CSS sheet, for this case, I really recommend you using styled-components to apply CSS-in-JS.

In the previous article, we spotted some limitations of our component especially when it came to dynamic content in the prefix label and the suffix.

On one side, we need to handle a maximum width for our label, while we also need the component to adjust its inner padding according to this dynamic width. Let’s go.

The result

To sum up, this is the final result:

And the final code:

Achtung!:

  • I am using Storybook, so that’s why I also included the propTypes. If you want to learn about how to use Storybook with PropTypes to make awesome quick stories and documentation, check out this article.

What was that?

Ok a lot of things were going on there. Take your time to take a look at the code.

Starting from our plain input with fixed labels. This is what we’ve done to make our input dynamically adjust to the label size:

  1. Add conditional rendering to both the prefix and the suffix, so they will only render when any of these props are defined. Else, they won’t render.
  2. Bind the value of the input too.
  3. We declare a ref into the prefix and the suffix that directly passes the node to the function getPrefixWidth / getSuffixWidth and retrieves the width of the rendered prefix/suffix and stores the data within a state through the useState React hook.
  4. We pass the variables suffixWidth and prefixWidth to the input so we can use them as params in our styled-components (lines 70–79).
  5. We bind the input padding props to the width of the suffix and prefix, obtained through the refs. This way we make sure that the content does not overwrite the other text (lines 36–38). In order to add some extra pixels to separate, we use a calc function.

From here on, you can iterate this as much as you need. Limiting the prefix width, or managing text over-flow… make it your own.

Peace and code

Nadine

--

--

Nadine Thery
urbanData Analytics

Frontend Developer 👩🏻‍💻, videogamer 🎮, boardgamer 🎲, plant-lady 🌿, mother-of-cat-and-dogs 🐱🐶🐶, environment-concerned🌎, youtuber, ocassional podcaster