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'));
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With