Skip to content
Advertisement

Pass props from in a child component to another component

My website have 2 pages:

  • A main page with some basic data from an API about each currencies and to link to get details about it.
  • A page that calls the API a second time and get the details on the currency that the user clicked on.

The way it works is that when the user click on a link, it gives the ID of the currency to the other page, which call the API and get the details.

The problem is that, since I only started learning React, I don’t understand how can I pass the ID when a link is clicked to the other page.

How the App.js is structured:

<div>
  <MainNavigation/>
  <Switch>
    <Route path='/' exact={true}>
      <MainPage data={this.state.apiResponse}/>
    </Route>
    <Route path='/coinDetails'>
      <CoinDetails/>
    </Route>
  </Switch>
</div>

How main page links looks like:

<tbody>{props.data.map((coin) => {
    return <tr key={coin.uuid}>
     <td><Link to={{pathname:'/coinDetails',state:{uuid:coin.uuid}}}>{coin.symbol}</Link></td>
     <td><Link to={{pathname:'/coinDetails',state:{uuid:coin.uuid}}}>{coin.price}</Link></td>
     <td><Link to={{pathname:'/coinDetails',state:{uuid:coin.uuid}}}>{coin.priceDiffInfos.priceDiff24h}</Link></td>
     <td><Link to={{pathname:'/coinDetails',state:{uuid:coin.uuid}}}>{coin.priceDiffInfos.tauxEvolution24h}</Link></td>
     <td><Link to={{pathname:'/coinDetails',state:{uuid:coin.uuid}}}>{coin.marketCap}</Link></td>
           </tr>})}
</tbody>

Here’s the detail page so far if it can be useful:

class CoinDetails extends React.Component {
constructor(props){
    super(props);
    this.state = {data : ''};
    }
async getCoinData(){
    await fetch('http://localhost:9000/coinDetails?uuid=%27+this.props.props)
    .then(response => response.json())
    .then(data => this.setState({data}))
    .then(console.log(this.state.data));
    }
componentDidMount(){
    this.getCoinData();
    };

render(){
    return (
    <div>
        <p>{this.state.data.name}</p>
    </div>)
    };
}

The coin details page works fine when I give an ID directly throught a props=”The ID” in the App.js file, the problem is really about how do I get the link to pass the ID of the coin to the details page when a link is clicked ?

I gave code samples of what I thought was relevant to the problem but I can of course give more if needed.

Advertisement

Answer

I think you best approach is use withRouter from react-router-dom

<Route path='/coinDetails/:id' />

then in you onclick function you must redirect to coinDetails/${coin.id}

 componentDidMount() {
        const id = this.props.match.params.id;
        this.getCoinData(id);
    }
 export default withRouter(YourComponent);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement