Pass data to component using state

Viewed 69

The ButtonList returns a list of filtered buttons that each link to a new page. Now I want that clicked-on button to also be displayed on the linked page. I don't quite understand how to save the data inside the button (a string) and pass it to the Button on the linked page. I assume I can do it with state (hence the buttonContent), but don't know how to write the code... Any help would be highly appreciated.

export default function Home() {
  const [searchValue, setSearchValue] = useState("");
  const [buttonContent, setButtonContent] = useState();

  const filteredData = data.filter(item =>
    item.name.toLowerCase().includes(searchValue.toLowerCase())
  );

  function handleSearch(value) {
    setSearchValue(value);
  }

  function handleButtonContent() {
    setButtonContent(!buttonContent);
  }

  return (
    <WrapperDiv>
      <StyledHeader />
      <Switch>
              
        <Route exact path="/home">
                
          <Searchbar onSearch={handleSearch} />
          <ButtonList
            data={filteredData}
            onClick={handleButtonContent}
          />
           
        </Route>
        <Route exact path="/home/content">
          <div>
            <Button light>{buttonContent}</Button>
          </div>
        </Route>
      </Switch>
    </WrapperDiv>
  );
}

1 Answers

Where you have the onClick={handleButtonContent} I would make it an arrow function and try using the event to change the state using the useState hook you've already implemented. (If I'm understanding you correctly).

So something like this:

onClick={e => {
    setButtonContent(e.target.value)
}}

and hopefully that should set the state to whatever you click on. Let me know if it works!

Related