Home > OS >  How to output components by some of their fields?
How to output components by some of their fields?

Time:01-02

There is a code, but I don't understand how to implement the logic. I need the element to be displayed when its curObject.cathegory field matches the argument passed to the function

ShowElementsByName = (cathegory) => {
        this.setState(
            this.currentnews = this.state.gettednews.map (
                (curObject) => {

                    if (curObject.cathegory === cathegory) {
                        return (
                            <BlogComponent
                                name = {curObject.name}
                                content = {curObject.content}
                                cathegory = {curObject.cathegory}
                            />
                        )
                    }
                    else {
                        return (
                            null
                        )
                    }
                }
            )
        )
    }

CodePudding user response:

First filter blogs/news in your category. Then map it to components (this can by used in render function) and... i don't get what you what to keep in state.

ShowElementsByName = (cathegory) => {
  const blogsInCategory = this.state.gattednews.filter(news => news.cathegory === cathergory);
  const blogsComponents = blogsInCategory.map(blog => (
          <BlogComponent
                name = {blog.name}
                content = {blog.content}
                cathegory = {blog.cathegory}
            />
  ))
  this.setState(blogsComponents)
  //or
  this.setState(blogsInCategory)
  // or what you need to keeep in this state
}
       

  • Related