In case you are not familiar with JSS that is css-in-js. JSS is an authoring tool in css which allows you to use javascript to describe styles in a declarative, conflict-free and reusable ways, (as stated on JSS website).
What is Float Label?
These are input with different behaviour from the usual or normal way we understand input. To explain more on how it works; when an input is empty, the placeholder will act normal as expected, then when filled with text, it moves to the top as shown below
Create a new project
Let’s create a new react project (I’m using Yarn but you can also use npm)
$ yarn create-react-app floating-input
Once the project is created completely, remember to clear out unwanted files, remaining the App.js, we then create a div that contains the input and label like this
Now we need to style the above component with JSS but first we install react-jss
$ yarn add react-jss
Then we import createUseStyles from the package react-jss as shown below
Then we create our useStyle function after that we can now start styling our component, feel free to style the component according to your taste.
Note how I used useStyle() inside the App function to access the selector or object key as it’s in the form of an object. Then we create our JSS syntax like this and in my case
As you can see how the css in js is accessed on the jsx, classes is use to store the returned from useStyles function then inside the className, we pick out each css that should affect the html element. Now our input looks like this
Next we’ll be adding css animation to the above input, we start with the interaction, which consists of a transition and the behaviour of position absolute and relative combined. First we add position relative to JSS floatingLabelWrap
Then we add position absolute to our label and a transform to center the label similar to the way placeholder works.
We have our output of floating input as this
Now we complete the animation with transition and to use focus-within to apply the translate effect to change the position and scale label
Now we have this result but with a minor problem that needs to be fixed.
To fix the error as noticed above, we’ll be doing so in reactjs as follow:
Firstly we create a state using useState hooks as shown below
Next we add another state to manage the text inputted
Next we add a function handler on input onChange to toggle our JSS active which we haven’t yet written.
Finally, we add the JSS style for active
We have a full javascript enabled floating label input completed
Remember there are always a better way to achieve this and if you do have a better way, please i would love to see it. Thanks
Based on Creating Floating Label/Placeholder for Input with ReactJS - DEV Community 👩💻👨💻
Top comments (0)