Search code examples
reactjsreact-routerreact-router-dombrowser-history

Problem when passing props using history.push() in react-router


I'm trying to pass props to another component in React using history.push(). My code looks like this:

 history.push({pathname:`/tickets/solveticket`,
                state:{ticket:this.props.ticketInfo, user:this.props.currentUser}}); 


 window.location.reload()

history is exported like this:

 import { createBrowserHistory } from 'history';

export const history = createBrowserHistory();

and my route configuration:

 import {BrowserRouter as Router,Route,Switch,Link } from "react-router-dom"; 
    <Router history={history}> 
    ... <PrivateRoute exact path="/" component={Dashboard} />
                    <Route exact path="/login" component={Login} />
                    <Route exact path="/register" component={Register} />


                    <PrivateRoute exact path="/dashboard" component={Dashboard} />  

`

and component that renders on /tickets/solveticket url takes history parameters like this:

constructor(props){
    super(props)
    this.state={
       ticketToSolve:this.props.location.state.ticket,
       currentUser:this.props.location.state.user
    }
}

and yet I'm getting this error:

TypeError: Cannot read property 'ticket' of undefined

I tried to wrap everything in withRouter and it still doesn't work. I also tried using this.props.history.push instead of exported history but in that case my history is not recognized..I've been googling for a day and run out of ideas what could I try, so if anyone has any idea please just write it down..thanks in advance :)


Solution

  • try

    constructor(props){
        super(props)
        this.state={
           ticketToSolve:"",
           currentUser:""
        }
    }
    componentDidMount(){
     if(this.props.location.state){
      this.setState({
           ticketToSolve:this.props.location.state.ticket,
           currentUser:this.props.location.state.user
        })
      }
    }
    

    Because some time you cant be so sure that variables are already set. Might be react render this code first.