Ayaz Uddin Ayaz Uddin - 3 months ago 107
React JSX Question

Passing a query string via react-router

Hello I am trying to pass information via a query string through react-router but i can not access it. I believe i followed the steps correctly but still nothing.

var UserContainer = React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
getInitialState: function() {
return{
id: this.props.data.id,
username: this.props.data.username,
html_url: this.props.data.html_url,
avatar_url: this.props.data.avatar_url
}
},
handleUserClick: function(event) {
event.preventDefault();

var id = this.state.id;
var username = this.state.username;
var html_url = this.state.html_url;
var avatar_url = this.state.avatar_url;

this.context.router.push({
pathname: '/user',
query: {
id: id,
username: username,
html_url: html_url,
avatar_url: avatar_url
}
});
},

//ROUTED TO THIS COMPONENT

var React = require('react');

var UserShowView = React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
componentDidMount: function() {
console.log(this.props.location.query)
},
render: function() {
return(
<div>
Hello
</div>
)
}
});

// REACT_ROUTER

var React = require('react');
var ReactRouter = require('react-router');
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;
var hashHistory = ReactRouter.hashHistory;
var IndexRoute = ReactRouter.IndexRoute;

var UsersIndexContainer = require('../containers/UsersIndexContainer');
var UserShowContainer = require('../containers/UserShowContainer');

var routes = (
<Router history={hashHistory}>
<Route path='/' component={UsersIndexContainer} />
<Route path='user' component={UserShowContainer} />
</Router>
);

module.exports = routes;


I keep getting this error

error

But as you can see the query string exists

enter image description here

Answer

Sounds like an issue with your Router configuration. Instead of declaring "/" and "user" at the same level, you want do embed "user" inside "/" like below:

var routes = (
  <Router history={hashHistory}>
    <Route path='/' component={UsersIndexContainer}>
        <Route path='user' component={UserShowContainer} />
    </Route>
  </Router>
);

Give this a try and let me know if that helps.