I would like to clear child functional component from parent after setting redux state
Here’s my code
const ParentContainer = (props) => { const onKeyDown = (keyPressed) => { if (keyPressed.key === 'Enter' && keyPressed.currentTarget.value.length > 0) { props.addMail(keyPressed.currentTarget.value); keyPressed.target.value = '' } } return (<Child onKeyPressDown={onKeyDown} />) }
On child component
const Child = (props) => { return (<Input placeholder="Add text list" fluid onKeyDown={ props.onKeyPressDown } />) } export default Child
Actually when I press enter
text stays , I would like to delete it.
I tried keyPressed.target.value = ''
in parent component but it’s not working
Advertisement
Answer
You need to introduce state in the Parent component. Then pass the state value to the input, and provide an onChange handler when the input changes. This is called a controlled component and you can read more about it here.
https://reactjs.org/docs/forms.html#controlled-components
const ParentContainer = (props) => { const [value, setValue] = useState(''); const onKeyDown = (event) => { if (event.key === 'Enter' && event.currentTarget.value.length > 0) { props.addMail(event.currentTarget.value); setValue(''); } }; return <Child value={value} setValue={setValue} onKeyPressDown={onKeyDown} />; };
const Child = (props) => { return ( <Input fluid value={props.value} onChange={(event) => props.setValue(event.target.value)} onKeyDown={props.onKeyPressDown} placeholder="Add text list" /> ); };