Search code examples
reactjstypescriptparent-childreact-component

Changing the state of a React Component


Maybe it's the way I am wording things, but I am not getting the answer I want on the following topic. So currently, my code looks like this (minus all the details):

<ClickAwayListener onClickAway={handleClickAway}>
  <Autocomplete options={someList} />
</ClickAwayListener>

So I have two questions.

  • Is Autocomplete component here considered to be an extension of ClickAwayListener? Is ClickAwayListener considered a parent component?
  • I want the handleClickAway function to change the options state within Autocomplete. How would I go about doing this?

I am pretty new to React, so I would appreciate any and all help. Thank you in advance.



Solution

  • It looks like most likely you are using your click away component not in a way it was intended to be used. It looks like it should be used with this technique.

    
    <ClickAwayListener onClickAway={handleClickAway}>
      {(isClickedAway) => (
        {/*or whatever api your Autocomplete has*/}
        <Autocomplete options={someList} isOpen={!isClickedAway} />
      )}
    </ClickAwayListener>
    
    

    As to your questions:

    • ClickAwayListener is a parent of Autocomplete. There's no such thing as extension in react tree.
    • in your handleClickAway you have to change someList. If it comes through the state, then with setState, if it comes from props - with a corresponding callback.