Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-router-dom and Redirect not being added to history?

Outline:

I'm currently trying to learn react/redux/router. As a practice project, I'm working on a basic contact/client management app. While using react-router-doms Redirect component. I can't get the back/forward navigation to work as expected.

Details:

I have a table with a list of entries located at /contacts/ and when you click on one of the table rows, I want to Redirect using a value set by the <tr>s onClick attribute.

The click on <tr key={d._id} onClick={()=>this.setState({ id: d._id })}> changes state.id to the clientIDs unique value. This results in a Redirect being true in the tables render method, triggering the Redirect.

render() { // render method of '/contacts/' {Contacts} component
    return(
        ... // table head
        { this.state.id && <Redirect to={"/contacts/card/"+this.state.id}/> }
        ...// table content
    )
}

This is the router which is located in the parent App.js

render() {
    return (
        <BrowserRouter basename="/" >
            <div>
                <NavBar/>
                <main>
                    <Switch>
                        <Route exact path="/" component={Login}/>
                        <Route 
                            exact path="/contacts" component={Contacts}/>
                        <Route
                            exact
                            path="/contacts/card/:clientID" component={ContactCard}/>
                    </Switch>
                </main>
            </div>
        </BrowserRouter>
    );
}

Question:

After the redirect, if you click the back button from /contacts/card/:clientID, the browser doesn't go back to /contacts/. instead, it cycles through any previous :clientID URLs that I've looked at.

I have tried wrapping the <tr> in a router <Link to={}> tag, but it destroyed styles.

Caveat: (this.state.id)

I know that I should be using Redux to hold the value of this.state.id for my redirect function. I haven't fully grasped how to mange multiple values with a single redux reducer yet. I will update question with the appropriate method once I do.

like image 937
denden Avatar asked Feb 11 '18 11:02

denden


1 Answers

Found the answer, I needed to add push to my <Redirect/> component like so.

<Redirect push to={`/contacts/card/${this.state.id}`}/>

From the docs:

<Redirect/>

push: bool

When true, redirecting will push a new entry onto the history instead of replacing the current one.

like image 59
denden Avatar answered Nov 18 '22 13:11

denden