Highlight searched text in React

All we need is an easy explanation of the problem, so here it is.

I am studying React and after implementing the filter functionality I got to think about how to highlight the matched word inside the searched string.

My App.js is:

import React, { Component } from 'react';
import ListValues from './ListValues';

class App extends Component {
  state = { 
    list: ['First string 1', 'second String 2', 'third string 3', 'teste rwe'],
    value: ''
   }

  render() { 
    return ( 
      <div>
        <input 
          value={this.state.value}
          onChange={e => this.setState({ value: e.target.value })} 
        />
        <ListValues list={this.state.list} value={this.state.value}/>
      </div> 
    );
  }
}

export default App;

And my ListValues.js file is:

import React from 'react';

const ListValues = (props) => {
    return ( 
        <div>
          <ul>
              {props.list.filter(name => {
                return name.toLowerCase().indexOf(props.value.toLowerCase()) >= 0;
              }).map((value, i) => {
                return <li key={i}>{value}</li>
              })}
          </ul>
        </div>
     );
}

export default ListValues;

The index.js file is the standard code:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';

ReactDOM.render(<App />, document.getElementById('root'));

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Unless I’m missing the point here, you could use styled components to conditionally apply styling (background colour) based on the value of props that you pass into your component.

import styled from 'styled-components'

const ListValue = styled.li`
  ${({ active }) => active && `
    background: blue;
  `}
`;

const ListValues = (props) => {
    return ( 
        <div>
          <ul>
              {props.list.filter(name => {
                return name.toLowerCase().indexOf(props.value.toLowerCase()) >= 0;
              }).map((value, i) => {
                return <ListValue active={true} key={i}>{value}</ListValue>
              })}
          </ul>
        </div>
     );
}

https://www.styled-components.com/docs

Method 2

I found a ready-made component for the requirement. If you want customization, please go through the source code and tweak as per your needs.

react-highlight-words

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply