How to filter an incoming prop in React?

Tags: ,



I’m trying to build a search bar using hooks but the props that I pass into my functional component gives me error and the output is never loaded. I pass the opt props from options.js to Filter.js. Here’s the code: Options.js

import Filter from './Filter'
import Option from './Option'

export default (props) => {
    return (
        <div>
            <button onClick={props.handleDeleteOptions}>Remove All</button>
            {props.options.length === 0 && <p>Please add option to get Started!</p>}
            {
                props.options.map((x) => <Option key={x} optionText={x}
                    handleDeleteOption={props.handleDeleteOption}
                />)
            }
            <Filter opt={props.options} />
        </div>
    );

}

Filter.js

export default (props) => {

    const [option, setOption] = React.useState(props);
    const [search, setSearch] = React.useState("");

    return (
        <div>
            <input
                onChange={e => {
                    const test = props.opt.filter(o => {
                        return o.toLowerCase().includes(e.target.value.toLowerCase());
                    });
                    console.log("Option: ", test);

                    setOption(test);
                    setSearch(e.target.value);
                }}
                type="text"
                value={search}
            />
            {props.opt.map(o => (
                <p key={o}>{o}</p>
            ))}


        </div>
    )
};

Answer

In you Filter.js you are mapping directly the props.opt. This doesn’t change when you do the filter. What changes is the state. There are two things you need to change for this to work:

  • Fix default option state: const [option, setOption] = React.useState(props.opt);
  • Fix the options map. Instead of props.opt, use option from the state.


Source: stackoverflow