Pass props for only one item in React

788 views Asked by At

I am building a blog app using React. I have an Index, Feed, and Post components. My Feed comp dynamically generates a list of posts. What I want is to click on one post in the Feed and have the page render only that post. I can't figure out how to capture/pass along the props info for only the post clicked to be rendered.

For brevity here's only the relevant code:

    this.state = {
  view: 'feed',
  blogs: []
}

  changeView(option) {
this.setState({
  view: option
});

}

renderView() { const {view} = this.state;

if (view === 'feed') {
  return <Feed handleClick={() => this.changeView('anypostview') blog={this.state.blogs} 
  view={this.state.view}/>
} else {
  return <Post blogs={this.state.blogs} view={this.state.view}/>
}

}

My click event is registering, but I don't know how to capture the props info for only the post that was clicked and send it to the Post component.

2

There are 2 answers

0
Vaibhav Rai On

During click the specific post, pass the post to the handleClick and then set the state of the parent component which in this is () => this.changeView('anypostview'), change it to (individualPost?: Post) => this.changeView('anypostview', individualPost) and use that, in that case, you will not need to define or use the state view

0
Furkan Aydoğan On
> blog={this.state.blogs}

this code will return you blank blog array .İ think you can write another function with setState for blog array

>   blogfunc = (blog) => {
>     this.setState({
>       blog: blog,
>     });   };

when you add new things in blog .Call this function and show on your page .