Berke Kaan Cetinkaya
Berke Kaan Cetinkaya

Reputation: 828

How to create a new page and route programatically in React.js with React Router

I'm building a blog website with React.js with React-router. I have a "blog.js" file that renders all titles of the blogs the page looks like this:

Blog.js

    function Blog() {
    
    
      return (
        <div>
          <Header />
          <div className="blog-page-title">
          <h1>Blog</h1>
          </div>
          <div className="blog">
            <Articles title="Title" text="lorem ipsum dolor amet" />
            <Articles title="Title" text="lorem ipsum dolor amet" />
            <Articles title="Title" text="lorem ipsum dolor amet" />
            <Articles title="Title" text="lorem ipsum dolor amet" />
            <Articles title="Title" text="lorem ipsum dolor amet" />
            <Articles title="Title" text="lorem ipsum dolor amet" />
            <Articles title="Title" text="lorem ipsum dolor amet" />
            <Articles title="Title" text="lorem ipsum dolor amet" />
      
          </div>
          <Footer />
        </div>
      );
    }

export default Blog;

enter image description here

When I click on the title, it should route to the corresponding article. But do I have to create a new Route and a new js file manually for each article to achieve this? For instance, can I do something like whenever there is a new Articles component in blog.js it will go and create a new route and a js file automatically?

Upvotes: 1

Views: 2079

Answers (2)

Sonfaya
Sonfaya

Reputation: 65

if you want an new specific page for each article, with his own url, you can you the useParam hooks.

In you app.js you create a route, with a slug, that identify your blog article.

<Route path="/blogs/:blogId  component={<Blog />}/>

Then acces to it using the Link tag as said by Sharvan in the above post.

blogs.map( blog => <Link to=`/blogs/${blog.id}` /> )

Then you can acces the slug in your blog component, so you will be able to fetch the corresping article.

const  { blogId } = useParams()
axios.get(`whatever/${blogId}`)

If you don't care of the url, you can just create one blog component that take a blogpost as props

Upvotes: 1

Shravan
Shravan

Reputation: 83

Use an api to return the blog post according to the selected blogId and then use Link from react router, set the 'to' attribute of Link to the corresponding page you have created for blogs and fill it up with the response you get from the api. You can refer to this documentation for routing: https://v5.reactrouter.com/web/api/Link

Upvotes: 0

Related Questions