4

I have a list of articles like this:

<div>
   {
       this.props.articles.map(article => {
            return (
                <ArticleCard key={article._id} article={article} />
            )
        })
    }
</div>

In the ArticleCard component, I'm only showing the title of my article. I want to put a link to it which would create new URL like 'article-title' and show the content.

How to achieve this?

5
  • if I understand you right, you want each card to have a link such as: /articles/article-title which will route to an Article component that will render the contents of article-title? (where article-title is a dynamic string)
    – Bill
    Nov 12, 2017 at 6:14
  • yes, article-title is dynamic string
    – Mushfiq
    Nov 12, 2017 at 6:15
  • and where is this "content"? I'm assuming it's a separate API call using the article-title as a query?
    – Bill
    Nov 12, 2017 at 6:17
  • yes, content will be another api call using article._id to render another component.
    – Mushfiq
    Nov 12, 2017 at 6:21
  • Now where is the problem? Have you read the docs at all? Use <Link to="/article1">Article1</Link> and <Route path="/:id" component={articleDetail}/> Nov 12, 2017 at 6:30

1 Answer 1

12

In your ArticleCard, you have to create a Link that will route to your full Article. This link will include the id of the article you are trying to render (ex. articles/${article._id})

By writing the Route path of the component Article as articles/:id, this will allow us to catch that id when Article is rendered (accessible via this.props.match.params.id)

Then, assuming that id is used to fetch the article from some other API, a good place to call that would be the componentDidMount of your Article component.

Here is a small example which may help you out:

import React from 'react'
import {
  BrowserRouter as Router,
  Route,
  Link,
  Switch
} from 'react-router-dom'

const ParamsExample = () => (
  <Router>
    <Switch>
      <Route exact path="/" component={ArticleList} />
      <Route path="/articles/:id" component={Article} />
    </Switch>
  </Router>
)

const article = {
  _id: 1,
  title: 'First Article'
};

const ArticleList = () => (
  <div>
    <ArticleCard key={article._id} article={article} />
  </div>
);

const ArticleCard = ({ article }) => (
  <div>
    <h2>{article.title}</h2>
    <Link to={`/articles/${article._id}`}>SEE MORE</Link>
  </div>
);

class Article extends React.Component {
  componentDidMount() {
    console.log('Fetch API here: ', this.props.match.params.id);
  }

  render() {
    return (
      <div>
        {`Fetching...${this.props.match.params.id}`}
      </div>
    );
  }
}

export default ParamsExample
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.