Amirreza
Amirreza

Reputation: 463

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
      
  }

Upvotes: 0

Views: 863

Answers (2)

Doublers Kay
Doublers Kay

Reputation: 176

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.

Upvotes: 1

Mohak Gupta
Mohak Gupta

Reputation: 193

Either you can use props to pass data in to the other component and render it when the onClick event is triggered or

you can navigate to a new page by onClick event and pass data into the header/route and access that data in the new page's component

Upvotes: 0

Related Questions