React JS: Pass A value from route to component

Viewed 39

I have these routes

<Router>
  <Switch>
    <Route path="/" exact component={Home} />
    <Route path="/reports" exact component={ReportPage} />
    <Route path="/reports/browse" exact component={ActiveReportsPage} />
    <Route path="/signin" exact component={SigninPage} />
  </Switch>
</Router>;

And I want to use this - /reports/browse/[ VALUE ] for example - (localhost:8000/reports/browse/1)

I need to access the VALUE from ActiveReportsPage to call an API. I need to pass in the Value which I get from the URL to Axios API call, how can I make it?

This is my ActiveReportsPage, as you can see

this.props.getReports(3); Calls the API and instead of 3 I should pass the VALUE

import React, {Component, useState} from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { getReports } from '../actions/reports';

export class ActiveReportsPage extends Component {

    static PropTypes = {
        reports: PropTypes.array.isRequired
    }

    componentDidMount() {
        this.props.getReports(3); {/* I need to pass in the argument from /reports/browse/< 1,2,3,4,5,6,7,8,9,10 > */}
    }

    constructor(props) {
        super(props);
        this.state = {
            isOpen: false
        };
    }

    render() {
        return (
            <h2>hello :P</h2>
        )
    }
};

const mapStateToProps = state => ({
    reports: state.reports.reports
});

export default connect(mapStateToProps, { getReports })(ActiveReportsPage);
2 Answers

You can pass params through the Router, which is accessible through the match prop:

<Router>
  <Switch>
    <Route path="/" exact component={Home} />
    <Route path="/reports/:parameter" exact component={ReportPage} />
    <Route path="/reports/browse" exact component={ActiveReportsPage} />
    <Route path="/signin" exact component={SigninPage} />
  </Switch>
</Router>;

and will then be accessible in the ReportsPage component as: this.props.match.params.parameter

also you can useParams

<Router>
  <Switch>
    <Route path="/" exact component={Home} />
    <Route path="/reports/:parameter" exact component={ReportPage} />
    <Route path="/reports/browse" exact component={ActiveReportsPage} />
    <Route path="/signin" exact component={SigninPage} />
  </Switch>
</Router>

and in component ReportPage use useParams

let { parameter } = useParams().

Related