r/learnreactjs • • Jan 24 '20

Passing data from a single JSON file from parent to child component in React using dynamic routes

Hello!

I'm trying to create a project that makes use of React dynamic routes.

Basically, my project does this: when I click on the Shop Page, a local JSON files is rendered in the Shop component, then when I click on an item from the Shop Component, a dynamic route is being created and its respective data is being show.

E.g. : instead of showing the 'Description Placeholder' text, I want to display the cars description. In the case of Ford KA, I want it to display 'Mini', for the Ford Fiesta I want 'Hatchback' and so on.

How can I pass this data from a parent to a child component? I looked up on Google and some tutorials make use of two API: they are comparing the id of one API which holds a list of items to the id of the other API which holds the item details. The problem is that I don't think I can do this with a local JSON file. I tried passing some data as props from the Shop component to ShopItems, but my code caused a plethora of errors in the console, so I ended up erasing that code to make this functional again.

Here is my Code and a CodeSanbox link:

App.js

import React from 'react';
import './App.sass';
import Nav from './components/Nav';
import About from './components/About';
import Shop from './components/Shop';
import ShopItem from './components/ShopItem';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';

function App() {
  return (
    <Router>
      <div className="App">
        <Nav />
        <Switch>
          <Route path='/' exact component={Home}/>
          <Route path='/about' component={About} />
          <Route path='/shop' exact component={Shop} />
          <Route path='/shop/:id' component={ShopItem} />
        </Switch>
      </div>
    </Router>
  );
}

const Home = () => {
  return (
  <div>
    <h1>Home Page</h1>
  </div>
)};

export default App;

Nav.js

import React from 'react';
import '../App.sass';
import { Link } from 'react-router-dom';
function Nav() {

  const navStyle = {
    color: 'white'
  };
  return (
    <div>
      <nav>
        <Link to='/'>
          <h3> Logo </h3>
        </Link>
        <ul className='nav-links'>
          <Link style={navStyle} to='/about'>
            <li>About</li>
          </Link>
          <Link style={navStyle} to='/shop'>
            <li>Shop</li>
          </Link>
        </ul>
      </nav>
    </div>
  );
}

export default Nav;

Nav.sass

nav
  display: flex
  justify-content: space-around
  align-items: center
  min-height: 10vh
  background: gray
  .nav-links
    width: 50%
    display: flex
    justify-content: space-around
    align-items: center
    list-style: none

Shop.js

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class Shop extends Component {

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

  componentDidMount() {

  fetch('./data.json')
  .then((res) => res.json())
  .catch(err => console.log(err))
  .then((data) => {
    //console.log('data:', data);
    this.setState({
      data: data
    })
  })
}

  render() {
    const { data } = this.state
    return (
      <div>
        {data.map(data =>
          <h1>
            <Link to={`/shop/${data.id}`}>{data.name}</Link>
          </h1>)}
      </div>
    )
  }
}

export default Shop;

ShopItem.js

import React, { Component } from 'react';
class ShopItem extends Component {

  render() {
    return(
      <div>Description Placeholder</div>
    )
  }
}

export default ShopItem;

data.json

[{"id": 1,"name": "Ford Ka", "description": "Mini"},
{"id": 2, "name": "Ford Fiesta", "description": "Hatchback"},
{"id": 3, "name": "Ford Focus", "description": "Hatchback"},
{"id": 4, "name": "Ford Mondeo", "description": "Sedan"}
]
9 Upvotes

4 comments sorted by

2

u/painya Jan 24 '20

This not what you need? Stack Overflow.

Edit: This answer looks easier

1

u/_sourDiesel Jan 24 '20

Holy shit.. I've banged my head on a wall all morning looking for answers on Google & SO. Since I'm a newbie to React my search keywords kinda suck: they were like "pass json data parent child dynamic routing".
Thanks a lot mate!

1

u/painya Jan 24 '20

For sure. I’m in the same boat as you!

1

u/_sourDiesel Jan 24 '20

Haha! Thanks again !