kika123
kika123

Reputation: 31

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 :)

Upvotes: 0

Views: 1893

Answers (2)

Muhammad Zeeshan
Muhammad Zeeshan

Reputation: 4748

You need to pass the values via 'history.push' like:

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

Hope this works for you.

Upvotes: 1

Rajan Lagah
Rajan Lagah

Reputation: 2528

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.

Upvotes: 0

Related Questions