Kyle Calica-St
Kyle Calica-St

Reputation: 2943

React Router v4 Nested Routes pass in match with Class Component

I am trying to have a nested route in my application. Where a component is declared with class syntax.

How do I pass match?

As you can see below, I am using the componentDidMount() function to pull in data, so I need to have the member function and I want this component to handle all my logic.

import React, { Component } from 'react';
import ListItem from './ListItem';
import Post from './Post';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

//holds the state for all the components
//passes into listing
//listing will re-direct to proper post using router

export default class Blog extends Component {

  constructor(props){
    super(props);

    this.state = {
      articles: [],
      content: null
    };
  }

  storeData = (data) => {
    const articles = data.map((post, index) => {
      return {
        key: index,
        title: post.title.rendered,
        content: post.content.rendered,
        excerpt: post.excerpt.rendered,
        slug: post.slug
      };
    });

    this.setState(
      {
        articles: articles
      }
    );
  };

  componentDidMount() {

    let articles = [];
    fetch('https://XXXXX.com/posts/')
      .then(data => data.json())
      .then(this.storeData).catch(err => console.log(err));

  }

  render(){

    return(
      <div className="blog">
          <h2> Listings </h2>
            { this.state.articles.map(post => (
              <Link to= { `path/${post.slug}` } >
                <ListItem
                  key={post.key}
                  title={post.title}
                  content={post.content}
                 />
               </Link>
            ))
          }
          <Route path='posts/:slug' component={Post} />
      </div>

    );
   }

}

Upvotes: 1

Views: 1388

Answers (1)

Kyle Calica-St
Kyle Calica-St

Reputation: 2943

Found it out!

If you look below in render, it was saved as a this.props!

However, now it renders the component below rather than replace to another page.

  render(){
    return(
      <div className="blog">
          <h2> Listings </h2>
            { this.state.articles.map(post => (
              <Link to={ `${this.props.match.url}/${post.slug}` } >
                <ListItem
                  key={post.key}
                  title={post.title}
                  content={post.content}
                 />
               </Link>
            ))
          }
          <Route path={ `${this.props.match.path}/:slug` } component={Post} />
      </div>
    );
   }

}

Upvotes: 1

Related Questions