Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router not rendering component

We are using react-router like so:

ReactDOM.render(
    <Router>
        <Route path="/" component={AnyPic}>
            <Route path="p/:photoId" component={PhotoView} />
        </Route>
    </Router>,
    document.getElementsByClassName("container")[0] 
);

var AnyPic = React.createClass({
    render: function() {
        return (
            <p>Hello world</p>
        )
    }
});

var PhotoView = React.createClass({
    render: function(){
        return (
            <p>This is the photo view</p>
        )
    }
});

After including react-router, what used to be just localhost:8000 started looking like localhost:8000/#/?_k=wulhmi. Not sure where those extra params came from.

Anyway, when trying to access localhost:8000/#/p/XYZ the page keeps going back to /. Any help would be much appreciated.

like image 936
Carpetfizz Avatar asked Nov 14 '15 03:11

Carpetfizz


People also ask

What is componentWillMount in react?

The componentWillMount() method allows us to execute the React code synchronously when the component gets loaded or mounted in the DOM (Document Object Model). This method is called during the mounting phase of the React Life-cycle.

Can route have render method?

Route render methodsThe recommended method of rendering something with a <Route> is to use children elements, as shown above. There are, however, a few other methods you can use to render something with a <Route> .

How do you pass props to a component rendered by react router v6?

If you need to access the v6 versions of these objects you will use the React hooks, useNavigate for a navigate function which replaced the history object, useParams for params instead of match. params , and useLocation for location .


1 Answers

The reason for that is because you are not rendering your children route(s). Check out the react router docs.

If you add this.props.children to your AnyPic component everything will work:

var AnyPic = React.createClass({
    render: function() {
        return (
            <div>
                <p>Hello world</p>
                {this.props.children}
            </div>
        )
    }
});

As @robertklep pointed out in the comment, the "extra" thing in the URL is being added as The Router uses Hash History by default, you probably want to use BrowserHistory to do that you need to install history module: npm install history See the docs here.

like image 72
knowbody Avatar answered Sep 30 '22 19:09

knowbody