J Seabolt
J Seabolt

Reputation: 2988

react-router-dom only works on reload

I am having trouble with an extremely simple redirect with react-router-dom.

When I click a div that triggers a redirect, the current component disappears. The URL changes to the appropriate route. But the new component does not appear. If I reload the page, I get the new component. What's going on?

Here is the component that cont:

import React from 'react'; 
import { connect } from 'react-redux'; 
import './BoardPost.css'; 
import { getNewQuiz } from '../../actions/quiz'; 
import { Redirect } from 'react-router-dom';

export class BoardPost extends React.Component {

    handlePostClick() {
        console.log(this.props.quiz.id)
        this.props.dispatch(getNewQuiz(this.props.quiz.title))      
    }

    render() {
        if (this.props.quizActive) {
            return <Redirect to="/quiz" />; 

        }
        else {
            return ( 
                <div className="board-post" onClick={() => this.handlePostClick()}> 
                    <img className="board-post-image" alt="planet image" src={this.props.quiz.image} />
                </div>
            )
        }
    }
}

const mapStateToProps = state => ({
    quizActive: state.answers.length > 0
}); 

export default connect(mapStateToProps)(BoardPost); 

Here is the wrapper component, which includes the different routes:

export class App extends Component {
  
  render() {
    return (
      <div className="App">
        <Header />
        <Route exact path="/" component={Board} />
        <Route exact path="/quiz" component={Quiz} />
        <Footer />
      </div>
    );
  }
}

When I click the div with className="board-post", I should be redirected. But I only see the new component once I reload. The old component disappears, the new route appears in the URL bar, but no new component until I reload the page manually.

Upvotes: 1

Views: 1841

Answers (1)

J Seabolt
J Seabolt

Reputation: 2988

I was missing export default withRouter(connect(mapStateToProps)(App)); at the bottom of the wrapper component.

Upvotes: 0

Related Questions