Search code examples
javascriptreactjscomponentsstateonchange

In React when in onChange function how to update another custom component's state and pass a value in?


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?


Solution

  • 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.