In a React app currently there is a drop down list that has an onChange event that calls a function. In that function (when the users selects a different choice in the ddl) what I would like to achive is to update another custom component & pass a value into that component.
So in the front end there is a simple drop down:
<Dropdown
value={selectedOption}
options={dropDownOptions}
onChange={onChange}
/>
Then there is an onChange function that gets fired when the drop down gets selected:
const onChange = React.useCallback(
e => {
const optionId = e.target.value;
const optionData = keyedOptions[optionId];
// refresh DownloadSelector custom component
// something like this which doesn't work {optionData.id && <DownloadSelector eventId={optionData.id} />} }
Also I am able to import the custom component at the top of the file normally such as:
import { DownloadSelector } from '../../../SearchAndSort/DownloadSelector';
The custom component when defining it has a value passed in like so:
export const DownloadSelector = ({eventId}) => {
If the whole page refreshes the custom DownloadSelector component will get uploaded. I would like that to happen in the onChange.
How in the onChange function can we update/reload/setState/refresh the DownloadSelector component?
const [eventId, setEventId] = React.useState()
const onChange = React.useCallback(() {
// ....
// replace newState with a updated value
setEventId( newState )
}, [])
return <DownloadSelector eventId={eventId} />
In DownloadSelector do something like this:
function useForceUpdate(){
const [value, setValue] = useState(0); // integer state
return () => setValue(value => value + 1); // update state to force render
}
const DownloadSelector = ({eventId}) => {
const forceUpdate = useForceUpdate();
// ....
return <Dropdown
value={selectedOption}
options={dropDownOptions}
onChange={onChange}
forceUpdate={forceUpdate}
/>
}
And then in onChange in Dropdown Component:
const onChange = React.useCallback(() {
// ....
forceUpdate()
}, [])
The answer for my question is in the custom component that I wanted to rerender when the drop down ( a different component) is changed is to define the variables that are changing in the custom component DownloadSelector in state (not a local let) such as:
const [isMyVar] = useState(false);
Then when isMyVar is updated the state changed & the component rerenders. The answer was not (what I originally thought) was to have the code in the onChange event of the 2nd component. I appreciate @Hostek for your help.