简体   繁体   中英

Pass props to a component, React Router V4

I have an app with this components tree:

App
   Header
   Main
     Searcher
     List_of_albums
       Album

So, the idea is that in the main page I have a searcher of albums and this displays a list of albums after the search. To do this, I am reading a .json file in the component Main and then the props are passed to List_of_albums and Album.

Everything works fine up to this point.

Now I want to acces with a buttom to the info of each Album in a new route: /id_of_the_album.

This buttom is localized in the component Album like this:

let albumLink = `/${this.props.id}`
<Link to={albumLink}></Link>

To do that, I tried this in the component App:

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

class App extends Component {
  constructor(){
  super()
  }

  render () {
   return (
     <Router>
      <Fragment>
       <Header />
        <Switch>
          <Route exact path='/' render={() => {
           return(
             <Main />
            )
          }} />

         <Route path='/:id_of_the_album' render={() => {
           return(
             <Profile />
           )
          }} />
          </Switch>
        </Fragment>
      </Router>
    )
  }
}

Where Profile is the new component to show the album details. In this new Component I would like to open the jsons of the individual albums with something like this:

import singlejson from '../data/""""herethe_id_of_the_album"""".json'

but How can I pass to the component profile the id_of_the_album??

Write it like this:

<Route path='/:id_of_the_album' render={props => <Profile {...props} /> } />

Now inside Profile component, it should be available by:

this.props.match.params.id_of_the_album

In react router, when you are routing from one component to another component, you will have an object match which has many properties within it. One among them is params which helps us to identify if any parameter is passed to the child component via the route.

In your case, you can just use match.params.id_of_the_album in your child component

This link gives more info on react router.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM