简体   繁体   中英

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?

react-router and react-router-dom are two complementary libraries that help you use the Browser history api using Javascript History package under the hood.

To implement what you want you should use BrowserRouter , Switch and Route Components within react-router-dom . BrowserRouter acts as a provider to its children of some utilities and the current location the history is in (current hostname, pathname, queryParams, etc.) while Switch and Route work together by Route being the component that bind a path you want with a React component to render and Switch the component that checks between all its child Route 's and Render the first that match the current pathname the history has, you can add a Route without a path prop so Switch falls back to it in case the current history location doesn't match any.

An example Would be something like this

import React from 'react'
import {BrowserRouter, Switch, Route} from 'react-router-dom'
import C1 from './C1'
import C2 from './C2'

export default class App extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return <div id="container">
            <BrowserRouter>
                <Switch>
                    <Route path="/view1" component={C1}/>
                    <Route path="/view2" component={C2}/>
                    <Route component={C1} />
                </Switch>
            </BrowserRouter>
        </div>;
    }
}

Now, there's multiple ways to navigate through the declared pages. One is to directly use the Link component and pass the pathname you want to go using the 'to' prop.

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

Link Actually renders an anchor with the href you gave through the to prop.

Another way to do navigate is to use the history api which is injected as a prop when rendered from a Route. This allows you to add some more logic before actually setting the new location. Here's a simple example

class C2 extends React.Component {
    /*other functions*/
    redirectToC1(){
        // do some extra logic you may want
        this.props.history.push("/view1")
    }
    render() {
        return(
            <div>
                <p>Other things</p>
                <a onClick={() => this.redirectToC1()}>Click me to Redirect to C1!</a>
                <p>Other things</p>
            </ div>
        )
    }
}

Be sure to dive in on the documentation to see more.

You can call the components as a functions, example:

export default class App extends React.Component {
    constructor() {
        super();
        this.state = {
            isActive: true
        };
    }
    C1 = () => {
        return <h1>C1</h1>;
    };
    C2 = () => {
        return <h1>C2</h1>;
    };
    render() {
        return <div id="container">{this.state.isActive ? this.C1 : this.C2}</div>;
    }
}

with the example above not using any routers. you can see the documentation how to install and use react navigation here: https://reactnavigation.org/docs/hello-react-navigation

You can use Scrollintoview You can check out this small demo I made for reference demo

This stackoverflow will also be useful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM