简体   繁体   中英

How to pass parameter to other component to show details of list from API on button click in react.js

I am new to reactJS. I have made a Listview which shows the list of posts. I have a button which will take me to the other component/page on which I want to show the comments on that post. How I will pass postId to the other component? And How I will pass that id to the API service to show the comment details.

Here is the code. This is the postComponent, Now I want to pass post.id to the commentComponent and I want to load that page on ShowComments button click.

I am using axios to get the data.

state = {
  posts: []
}

componentDidMount() {
  axios.get(`https://jsonplaceholder.typicode.com/posts`)
    .then(res => {
      const posts = res.data;
      this.setState({ posts });
    })
}
render() {
 return (
  <div className="userlist">
  <ul>
    { this.state.posts.map((post , index) =>
      <li key={post.id}>
        <div className="user_name"><span>Post:</span> {post.title}</div>
        <div className="user_usernamename"><span>Details:</span>{post.body}</div>
        <div className="actionButtons">
          <button>Show Comments</button>
          <button>Flag</button>
        </div>
      </li>
  )}
  </ul>

  </div>

  )
 }

Thanks.

Use react router dom https://www.npmjs.com/package/react-router-dom and make a function that will be triggered on button click that will take you to other page where you will put axios call in componentWillMount (or componentDidMount) that will get you your data.

Id of your post will be passed to react router dom as an argument to the triggering function

You can achieve this by adding an onclick event and attaching a handler to it. Then you can bind that handler to this and the post.id

Read more here: https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers

Whenever the post will be clicked this handler will be called and you can handle the axios's call internally here or if your CommentComponent lives in the parent file then you can bubble up the click via the props and let the parent component make the API call and finally display the comments.

Something like so:

state = {
  posts: [],
  comments: [],
  showComments: false
}

componentDidMount() {
  axios.get(`https://jsonplaceholder.typicode.com/posts`)
    .then(res => {
      const posts = res.data;
      this.setState({ posts });
    })
}

handleCommentClick (postId) {
 // Either set the state and then do a conditional rendering
 // or handle this change in the parent component

 // if handled in parent component
 this.props.handleCommentClick && this.props.handleCommentClick(postId); 

 // If handling it here then..
 // First make the API call using axios
 axios.get(`https://jsonplaceholder.typicode.com/comments/${postId}`)
  .then(res => {
    this.setState({
      comments: res.comments,
      showComments: true
    });
  });
}

render() {
 return (
  <div className="userlist">
  <ul>
    { this.state.posts.map((post , index) =>
      <li key={post.id}>
        <div className="user_name"><span>Post:</span> {post.title}</div>
        <div className="user_usernamename"><span>Details:</span>{post.body}</div>
        <div className="actionButtons">
          <button onClick={this.handleCommentClick.bind(this, post.id)}>Show Comments</button>
          <button>Flag</button>
        </div>
      </li>
  )}
  </ul>
  {
    // Whenever show comments is made true, this component will render
    showComments &&
      <CommentsComponent comments={this.state.comments} />
  }

  </div>

  )
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM