Search code examples
javascriptreactjsreact-props

How to pass state from component to another external component?


I have a state (stateRegister) that has {username, email, password} stored in component called BasicForm.js:

const BasicForm = () => {
  const [stateRegister, setStateRegister] = useState({
    username: '',
    email: '',
    password: '',
  })

  function handleChange(e) {
    const value = e.target.value
    setStateRegister({
      ...stateRegister,
      [e.target.name]: value,
    })
    console.log(stateRegister)
  }

  return ( //... )
}

I want to pass its data to an other component Review.js:

export default function Review() {
    //call and use passed stateRegister data here
}

How to do that?


Solution

  • either use useContext() or pass it as a prop. (so something like:

    function BasicForm () {
    ...
    return (<Review stateRegister={stateRegister} />)
    }
    
    
    function Review ({ stateRegister }) { ... }