Search code examples
javascriptreactjsstatereact-props

passing data to componnet onClick in react js


We have 2 components. one is Test1 and the second one is Test2. My question is how we can pass data from component Test1 to Test2(they are separated components.) onClick event. : for e.g a function like this:

  const ClickHandler =()=>{
        //pass data to Test2
      
  }

Solution

  • I think there will be two methods to do this.

    1. Be a child of the same parent and share props.
      import {useState} from "React"
       
      const TestOneComponent = ({value}) => (
        <span>{value.toString()}<span>
      )
    
      const TestTwoComponent = ({value, onClick}) => (
        <span>{value.toString()}</span>
        <button onClick={onClick}>Increase Value</button>
      )
    
      const ParentComponent = () => {
        const [value, setValue] = useState(0)
    
        const onClick = () => {
          setValue(value + 1)
        }
    
        return (
          <>
            <TestOneComponent value={value}>
            <TestTwoComponent value={value} onClick={onClick}>
          </>
        )
      }
    
    1. Manage store and pass props to those two components.