jason135
jason135

Reputation: 189

React: How to update a component from another

I have a CRUD page that includes two components, <Create /> and <List />. Users can update/delete in the <List /> component.

I have no access to the newly created value. Is there a way I can send a signal from the <Create /> component to the <List /> component so <List /> can query the back-end for the new data?

<>
  <Create onCreate={handleCreate} />
  <List onDataChange={handleDataChange} />
</>

Upvotes: 0

Views: 146

Answers (1)

chuck_d
chuck_d

Reputation: 131

There are a couple ways to do this, but the simplest way would be to have the reference to that data be in the parent component for both of these other components like this:

function Parent() {

  const [data, setData] = React.useState([])
  
  const handleCreate = (item) => {
    setData(prevData => [...prevData, item])
  }

  return (
    <>
      <Create onCreate={handleCreate} />
      <List data={data} />
    </>
  )
}

Upvotes: 1

Related Questions