Search code examples
reactjsroutescomponents

React display page with properties by its id


So I have multiple projects and when I click "See Project" button I want to display a page where I can see only one project information by its ID (using MongoDB)

My App Route code:

  <div className="App">
    <HashRouter>
      <div>
       <Navigation />
        <Switch>
          <Route exact path="/" component={Dashboard}/>
          <Route path="/projects" component={DisplayProjects}/>
         <Route path="/projects/:id" component={Project}/>
        </Switch>
      </div>
    </HashRouter>
  </div>

And my Page that only have info by ID:

import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';

import './Project.css';

class Project extends Component {
  constructor(props) {
    super(props);
    this.state = {
        project: {}
    };
}
      
render() {

    return (
        <div className="Projects">
        <h1>
           {this.state.project.title}
        </h1>
        <h1>
           {this.state.project.typeOfProduction}
        </h1>
      </div>
       );
   }
}
export default Project;

my DisplayProjects Page:

import React, { Component } from 'react';

import CardProjects from '../../components/pages/Projects/CardProjects/CardProjects';
import Project from '../../components/pages/Projects/Project/Project'

import './DisplayProjects.css';



class DisplayProjects extends Component {

constructor(props) {
    super(props);
    this.state = {
        projects: []
    };
}


componentDidMount() {
    fetch('/dashboard/projects')
        .then(response => {
            return response.json()
                .then(projects => {
                    console.log(projects);
                    this.setState({
                        projects: projects
                    });
                });
        });
}
render() {
    //  console.log("This.state.projects " + this.state.projects);
    const projects = this.state.projects.map(project => {
        return <CardProjects
        key={project._id}
        id={project._id}
        title={project.title}
        typeOfProduction={project.typeOfProduction}
        />
    });


    return (
        <div>
            <section className="DisplayProjects container">
                  {projects}
            </section>
        </div>
    );

}


export default DisplayProjects;

and the "See Project" button Link Route is:

    <NavLink to={`/projects/${props.id}`}><button 
   type="button" className="btn btn-outline-secondary">See 
   Project</button></NavLink>

this NavLink Works! it appears their own ID but doesn't appear/render my Page "Project" with only that info, only appears on the browser route

enter image description here


Solution

  • Add exact property in the Route of DisplayProjects otherwise react-router will show DisplayProjects for all routes beginning by 'projects' so 'projects/1234' also.