Sherly Septiani
Sherly Septiani

Reputation: 59

How to pass URL params to render function in ReactJS

I have React Router that looks like this:

<Switch>
  <Route exact path="/" render={() => <DashboardView {...dashboardViewProps} />} />
  <Route path="/blocks" render={() => <BlocksView {...blocksViewProps} />} />
  <Route path="/chaincodes" render={() => <ChaincodeView {...chaincodeViewProps} />} />
  <Route path="/channels" render={() => <ChannelsView {...channelsViewProps} />} />
  <Route path="/network" render={() => <NetworkView  {...networkViewProps} />} />
</Switch>

I want to add new route like this:

<Route path="/transactions/:txId" render={() => <TransactionsView {...transactionsViewProps} />} />

How could I pass the txId to the TransactionView constructor which now looks like this:

constructor(props) {
    super(props);
}

Thank you

Upvotes: 1

Views: 818

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 282040

txId is available to the Router component though the router props, and when you render a component through render props, you need to pass the router props to the component

<Route path="/transactions/:txId" render={(routerProps) => <TransactionsView {...transactionsViewProps} {...routerProps}/>} />

and then in the component you can get it like

constructor(props) {
    super(props);
    this.txId = props.match.params.txId
}

Upvotes: 2

Related Questions