0

I am trying to pass a whole object from one component to another on button click.

I have tried using Link and Router, but I still cannot see the object inside the props of the destination component.

I am using the onClick handler handleReportIncident to pass an available object while Routing to this component. The handleReportIncident function is bound at the top.

    handleReportIncident() {
        const { trip } = this.state;
        this.props.history.push(`/app/new`)
        return (
            <div>
                <New trip={trip} />
            </div>
        )
    }

    render() {

        return (

                    <Button
                        variant="contained"
                        color="primary"
                        className={classes.toolbarButton}
                        onClick={this.handleReportIncident}
                    >
                        <AddIcon />
                        Incident
        </ Button>
)}

Inside of New component I have :

class New extends Component {
render() {
const {trip} = this.props;
console.log("the trip is", trip);
return(
...
)
}
New.propTypes = {
    trip: PropTypes.object.isRequired,
};

Note: I am using material UI as a theme.

The Log inside the New component is the trip is undefined.

ksenia
  • 187
  • 7
  • 23
  • you can't return components from event handlers ... you need to store data above router (redux, top app component state, context api ...etc.) – xadm May 27 '19 at 22:16
  • @xadm, thank you, how would you do it using top app component state? can you share resources? example? – ksenia May 27 '19 at 22:59
  • Using Link `to.state` is good, you can search for other solutions like [this with redux](https://stackoverflow.com/a/47958053/6124657) ... just update app state/store and redirect – xadm May 28 '19 at 08:57

1 Answers1

2

You can wrap your desired object in the state of the Link. See example below.

// Main Component from which you want object passed

render() {

  return (
    <Link to = {{
      pathname: '/app/new',
      state: {
        trip: this.state.trip
      }
    }}>
      <AddIcon /> Incident 
    </Link>
  )
}

// New Component get desired object from this.props.location.state

class New extends Component {
render() {
const { trip } = this.props.location.state
console.log("the trip is", trip);
return(
...
)
}
New.propTypes = {
    trip: PropTypes.object.isRequired,
}

For more info on how it works head over to this tutorial: https://tylermcginnis.com/react-router-pass-props-to-link/

Rikin
  • 5,351
  • 2
  • 15
  • 22