1

This is my data (in a seperate JS file):

const someData= [
    {
        id: 1,
        title: "Article 1",
        desc: "Some description lorem ipsum",
    },
    {
        id: 2,
        title: "Article 2",
        desc: "Some description lorem ipsum",
    },
    {
        id: 3,
        title: "Article 3",
        desc: "Some description lorem ipsum",
    }
]

export default someData;

Now I'm mapping the data like this:

- Articles.js file

const articleItems = this.state.someData.map(item => 
         <ArticleItem key={item.id} item={item} 
      />)

return(
   <div>{articleItems}</div>
)

And listing all articles with only the article title displayed in ArticleItem component.

- articleItem.js file

return(
   <h1>{props.item.title}</h1>
)

How can I create so you can click on an article title in the list, which would then go to that specific article (url should be /article/id) and display all data for that specific article?

matje
  • 41
  • 4
  • Possible duplicate of [React Router Pass Param to Component](https://stackoverflow.com/questions/45898789/react-router-pass-param-to-component) – Bruno Paulino Feb 12 '19 at 19:06
  • I've checked before but unfortunately it didn't help me. Maybe I'm doing something wrong. – matje Feb 12 '19 at 19:57

1 Answers1

0

Use React Routers Version 4 to achiever this.

Article.js file-

const articleItems = this.state.someData.map(item => 
        <Route key={item.id} path=`/${item.title}/${item.id}` render={
            <ArticleItem 
                {...props}
                item={item}
            />

        } /> 
      />)

return(
   <div>{articleItems}</div>
)

In the file where you are rendering the Links render like this.

render() {
    return(
        <Link to=`/${item.title}/${item.id}`>{item.title}</Link>
    );
}

Don't forget to import Route and Link. Hope this helps.

JupiterAmy
  • 374
  • 2
  • 11