Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight searched text in React

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'));
like image 387
Matheus Sant'ana Avatar asked Sep 12 '25 03:09

Matheus Sant'ana


2 Answers

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

like image 109
ThatCoderGuy Avatar answered Sep 14 '25 18:09

ThatCoderGuy


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

like image 38
Prateek Kumar Dalbehera Avatar answered Sep 14 '25 16:09

Prateek Kumar Dalbehera