Shiny
Shiny

Reputation: 135

Passing data from parent component to child component on button click

I am new to React. What I am trying to achieve is to render a new component when a button is clicked in the parent component and pass some data from parent to child. I am able to navigate from parent to child but I am unable to pass data. Below is the simplified version of my code. My parent component - Posts.js

    const Posts = (props) => {
      const { posts, loading } = props;
      var nameArray = posts.map(function (el) {
        return el.kiosk_name;
      });
      console.log(nameArray);
      if (loading) {
        return <h2>Loading All Kiosks....</h2>;
      }
      return (
        <div>
          <Link to={`/kiosks/addkiosk`}>
            <button className="AddBtn" onClick={nameArray}>ADD</button>
          </Link>
)}

Child component - AddKiosk.js

export const AddKiosk = (props) => {
  const { nameArray } = props;
  console.log(nameArray);
}

I am trying to pass the nameArray from onClick but the console log of AddKiosk shows - Undefined. Please let me know where am I going wrong. Sorry if my question is very trivial. Thanks in advance.

Upvotes: 1

Views: 573

Answers (1)

Ajeet Shah
Ajeet Shah

Reputation: 19813

I am assuming that you are using react-router-dom and when you click on ADD button, it takes you to URL /kiosks/addkiosk and renders the AddKiosk component.

Expected:

You want to send nameArray data to AddKiosk component.

Solution:

You can pass some data as location state using Link's to prop. You may read this related post.

Code

const Posts = (props) => {
  const { posts, loading } = props
  var nameArray = posts.map(function (el) {
    return el.kiosk_name
  })
  console.log(nameArray)

  if (loading) {
    return <h2>Loading All Kiosks....</h2>
  }

  return (
    <div>
      <Link to={{
        pathname: `/kiosks/addkiosk`,
        state: nameArray // HERE, passing data using Link
      }}>
        <button className="AddBtn">
          ADD
        </button>
      </Link>
    </div>
  )
}

export const AddKiosk = (props) => {
  const location = useLocation()
  console.log(location.state) // HERE, it will print data
  return <>i am AddKiosk</>
}

Upvotes: 1

Related Questions