Pass Selected Value to Parent Component #4555
-
Hi folks, I started using react-select recently and wanted to set state with the value of a selected option. I imported the "select"-component "find.js" to my main component "items.js" and so far it's fine, I can use the select. If I want to get the selected value in my child component it works fine. However, if I try it as I usually do with child components in a parent component, e.g. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Greetings @bluecrunch , React advocates a one way data flow, so the basic methodology for something like this would be to create the Select as a controlled component in which the parent provides both the value and setValue method as props to the child. // find.js
const Find = props => {
const { selectedValue, setSelectedValue } = props;
const onChange = option => {
// do stuff with selected object and then send selected value to parent through provided prop
setSelectedValue(option);
}
return <Select value={selectedValue} onChange={onChange} />
}
// items.js
const Items = props => {
const [ selectedValue, setSelectedValue ] = useState();
return (
<Find selectedValue={selectedValue} setSelectedValue={setSelectedValue} />
)
} |
Beta Was this translation helpful? Give feedback.
Greetings @bluecrunch ,
React advocates a one way data flow, so the basic methodology for something like this would be to create the Select as a controlled component in which the parent provides both the value and setValue method as props to the child.