This component searches courses with using keywords. I need some help reengineering it to be a functional component. I need some guidance so I would also learn to do this step by step.
const courses = [
'Economics',
'Math II',
'Math I'
];
class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
search: []
}
}
render() {
let options;
if (this.state.search.length) {
const searchPattern = new RegExp(this.state.search.map(term => `(?=.*${term})`).join(''), 'i');
options = courses.filter(option =>
option.match(searchPattern)
);
} else {
options = courses;
}
return (
<div>
<input type="text" onChange={(e) => this.setState({ search: e.target.value.split(' ') })} />
<ul>
{options.map((option, i) =>
<li key={option + i}>{option}</li>
)}
</ul>
</div>
)
}
}
ReactDOM.render(<SearchBar />, document.body)
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
If you know the life cycle of a class component you will have no trouble understanding how a functional component works.
The main interest of functional components is the use of hooks.
Here is the doc from react about the components : https://fr.reactjs.org/docs/components-and-props.html
Here is the doc from react about the hooks : https://fr.reactjs.org/docs/hooks-intro.html
Here is an example for your functional component :
function SearchBar() {
const [search, setSearch] = useState([]);
let options;
if (search.length) {
const searchPattern = new RegExp(search.map(term => `(?=.*${term})`).join(''), 'i');
options = courses.filter(option =>
option.match(searchPattern)
);
} else {
options = courses;
}
return (
<div>
<input type="text" onChange={(e) => setSearch(e.target.value.split(' '))}/>
<ul>
{options.map((option, i) =>
<li key={option+i}>{option}</li>
)}
</ul>
</div>
)
}
ReactDOM.render(<SearchBar />, document.body)