user5640752
user5640752

Reputation: 101

react router passing variable/state to new route?

I have a dynamic variable that is made in one component and then that component routes to another component. How do i pass the variable?

COMPONENT A

import React, { Component } from 'react';

class Event extends React.Component {
   makeVariable(event)
   { myVariable = '123abc' }

   {window.location.replace("/B")}

   render () { return (html for page A)
}
export default A;

COMPONENT B

import React, { Component } from 'react';

class B extends Component {
    render(){ console.log(myVariable)}
}
export default B;

ROUTES FILE

export const makeMainRoutes = () => {
  return (
    <Router history={history}>
        <div>
          <Route path="/A" render={(props) => <App auth={auth} {...props} />} />
          <Route path="/B" render={(props) => <Home auth={auth} {...props} />} />
)}

Upvotes: 1

Views: 1161

Answers (2)

Dženis H.
Dženis H.

Reputation: 7822

I'm not quite sure if this is what you're asking, but I'll assume it is :)

Let's say this is the data you want to send from component A to component B.

const yourData = [{name: 'Tom', age: 28}, {name: 'Sara', age: 25}, {name: 'Rick', age: 34}];

You can use the Link tag to pass the data from one component to another, like this:

<Link to={{ pathname: `/component/b`, state: { yourData } }}></Link>

[maybe add a button tag so a user can click on it, go to the next route, where the necessary data is going to be passed] ... and then, in component B you can access your data like this:

const passedData= this.props.history.location.state.yourData;

Upvotes: 1

Alan Friedman
Alan Friedman

Reputation: 1610

In React Router 4 you should be able to access query params via props.location.search.

Component A

window.location.replace(`/B?myVariable=${myVariable}`);

Component B

import queryString from 'query-string';

render() {
  console.log(queryString.parse(this.props.location.search).myVariable));
}

Upvotes: 0

Related Questions