I would like to clear child functional component from parent after setting redux state
Here’s my code
JavaScript
x
11
11
1
const ParentContainer = (props) => {
2
const onKeyDown = (keyPressed) => {
3
if (keyPressed.key === 'Enter' && keyPressed.currentTarget.value.length > 0) {
4
props.addMail(keyPressed.currentTarget.value);
5
keyPressed.target.value = ''
6
7
}
8
}
9
return (<Child onKeyPressDown={onKeyDown} />)
10
}
11
On child component
JavaScript
1
10
10
1
const Child = (props) => {
2
return (<Input placeholder="Add text list"
3
fluid onKeyDown={
4
props.onKeyPressDown
5
}
6
/>)
7
8
}
9
export default Child
10
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
JavaScript
1
12
12
1
const ParentContainer = (props) => {
2
const [value, setValue] = useState('');
3
4
const onKeyDown = (event) => {
5
if (event.key === 'Enter' && event.currentTarget.value.length > 0) {
6
props.addMail(event.currentTarget.value);
7
setValue('');
8
}
9
};
10
return <Child value={value} setValue={setValue} onKeyPressDown={onKeyDown} />;
11
};
12
JavaScript
1
12
12
1
const Child = (props) => {
2
return (
3
<Input
4
fluid
5
value={props.value}
6
onChange={(event) => props.setValue(event.target.value)}
7
onKeyDown={props.onKeyPressDown}
8
placeholder="Add text list"
9
/>
10
);
11
};
12