React Router: How to redirect to a different component when a link/button is clicked?

Just started learning web-dev recently so please excuse my perhaps naive question.

I’ve seen many examples of using <Link> and <Route> to update the page. However, most contain a fixed navigation bar where the links sit, and the components themselves have but static content.

It’s not immediately clear to me as to how to correctly update the page if the links/buttons are inside the child component. For example, given a container:

<div id='container'><h1>components should be rendered in here, but only 1 at a time.</h1></div>

and 2 components, C1 and C2:

class C1 extends React.Component {
    /*other functions*/
    render() {
        return(
            <div>
                <p>Other things</p>
                <Button>Click me to Redirect to C2!</Button>
            </ div>
        )
    }
}

class C2 extends React.Component {
    /*other functions*/
    render() {
        return(
            <div>
                <p>Other things</p>
                <a>Click me to Redirect to C1!</a>
                <p>Other things</p>
            </ div>
        )
    }
}

Assume these 2 components are to be rendered under the ‘container’ div, with C1 being the default component.
How should I set up react-router to navigate between C1 & C2, and theoretically for more than two components?

Source: Ask Javascript Questions

LEAVE A COMMENT