How to highlight text based on user input with React.js ?
The following approach covers how to highlight text input given by users in ReactJS. It is a simple effect you can add to any ReactJS website.
- Basic knowledge of npm & create-react-app command.
- Basic knowledge of styled-components.
- Knowledge of useState() React hooks.
- Knowledge of onChange() event.
Basic Setup: You will start a new project using create-react-app so open your terminal and type:
npx create-react-app react-highlight-text
Now go to your react-highlight-text folder by typing the given command in the terminal:
Required module: Install the dependencies required in this project by typing the given command in the terminal:
npm install --save styled-components
Now go to the src folder and create a file AppStyles.js.
Project Structure: The file structure in the project will look like this:
Example: We create a state with the first element input as an initial state with a value of the empty string and the second element as function setInput() for updating the state. Then a function is created by the name toggleInput which sets the value of the state to the value we enter in our input field.
We set up our input field as a controlled component so that it updates the state accordingly. When we enter a value in our Input field, toggleInput function gets triggered through onChange event which sets the state to that entered value. We also use the state value just below our input field in InputHighlighter element styled with a top border (which covers our input field’s bottom border). This way, we use React state to update the value of both the Input field and InputHighlighter. So, when we enter a value in our input field, that value also gets updated in the InputHighlighter. That’s why the latter’s borderline keeps on increasing while we enter a text, but we don’t see it because we have set the CSS overflow property to none for our InputHighlighter.
This makes the webpage users think that the input field is actually highlighting the text they are entering. But in reality, it doesn’t happen that way. They just see the top border of another element as an input highlighter.
Step to Run Application: Run the application using the following command from the root directory of the project.
Output: Now open your browser and go to http://localhost:3000/, you will see the following output. See how borderline increases when we enter a text and starts decreasing when we remove the characters one by one.