1

I have a react app where the react-router is initialized in the App.js. When the url is localhost:3000/id the Home component is been rendered to the App.js, but i need to get the id variable from the App.js to run the initBusinessDetails() how can I access the id variable from the App.js.

App.js code

import React from 'react'
import axios from 'axios';
import ReactLoading from 'react-loading';
import { Route, Link, BrowserRouter as Router } from 'react-router-dom'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getBusiness } from './actions/GetBusinessDetails';
import Home from './components/Home';
import Categories from './components/Categories';

class App extends React.Component {




  initBusinessDetails(){
    console.log(this.props)

    const { params } = this.props.match
    axios.get(`http://localhost:8081/getBusiness?businessId=`+params.id)
    .then(res => {
      this.props.getBusiness(res.data)
    })
  }

  componentDidMount(){
    this.initBusinessDetails();
  }

    render() {
        return (

           <div>
             {!this.props.business ?

                <div>
                  <ReactLoading type="bars" color="#000"/>
                </div>:
                <div>
                  <Router>
                    <Route exact path="/:id" component={Home}/>
                    <Route exact path="/:id/categories" component={Categories}/>
                    </Router>
                </div>
            }

          </div>
        )
      }
}

function mapStateToProps(state){
  return{
    business:state.business
  }
}

function matchDispatchToProps(dispatch){
  return bindActionCreators({getBusiness : getBusiness},dispatch)
}
export default connect(mapStateToProps,matchDispatchToProps)(App)
Marques
  • 15
  • 1
  • 6
  • https://stackoverflow.com/questions/35352638/react-how-to-get-parameter-value-from-query-string Check this post on how to get parameters from querystring – Mario Murrent Jan 08 '20 at 14:08

1 Answers1

0

Accessing Match Params

A component being rendered under the component prop from react-router-dom also receives a match prop.

You’ll have access to match objects in various places:

  • Route component as this.props.match
  • Route render as ({ match }) => ()
  • Route children as ({ match }) => ()
  • withRouter as this.props.match
  • matchPath as the return value

To access the id from it:

initBusinessDetails() {
  const { params } = this.props.match;
  axios.get(`http://localhost:8081/getBusiness?businessId=${params.id}`)
    .then(res => {
      this.props.getBusiness(res.data)
    });
}

But this Code is Outside my Router

Now this code is outside of your router, so you need to render something inside your router that can call that function. This is easy since you are still only using a Router so all matched routes are rendered (As opposed to a Switch which only returns the first matched route). Render another route with an inline functional component. Could do class-based as well, but would require a tweak in order to work. Let me know if this is the case.

<Route
  exact
  path="/:id"
  component={({ match }) => {
    // add any logic here to do anything when this component is 
    // mounted/rendered, like call `initBusinessDetails` with 
    // the `id` param
    return null; // return nothing to the UI
  }}
/>

Now, this will trigger that function whenever the router rerenders that route, so you may need to add logic out in App and your axios call to ensure you only initialize once. If you can use hooks, then an useEffect hook right in the inline functional component would do the trick.

initBusinessDetails(id) {
  axios.get(`http://localhost:8081/getBusiness?businessId=${id}`)
    .then(res => {
      this.props.getBusiness(res.data)
    });
}

...

<Route
  exact
  path="/:id"
  component={({ match }) => {
    useEffect(
      () => initBusinessDetails(match.params.id),
      [] // call only once when mounted
    );
    return null; // return nothing to the UI
  }}
/>
Community
  • 1
  • 1
Drew Reese
  • 165,259
  • 14
  • 153
  • 181