Passing data between components into React (props)

74 Views Asked by At

Into DisplayVisit component I have displayed data:

<div>
{(this.state.allVisit.length > 0) ? this.state.allVisit.map(data => {

    return (
        <div key={data.id} className="card-header mb-2" style={{ background: "#F0F3F7" }}>
            <div className="form-group">
                <label><b>VisitName:</b> {data.dataContext.VisitName} &nbsp;</label>
             </div>                                                     
                                                    
            <div className="form-group">
                <Link to={`/visit/${data.id}`} className="btn btn-secondary btn-sm" >
                    <i className="fas fa-arrow-circle-right" /> Details
                </Link>
            </div>
        </div>
    )
    }) : (
        <div className="card-header p-3 mb-2 text-black">
            <label><b>Empty</b></label>
        </div>
     )
}

</div>

When user click Details is moved to next component VisitDetails - this is working.

App.js

<Route exact path="/visit/:id" component={VisitDetails}/>

Then I want have access to id and data.dataContext:

class VisitDetails extends Component {

    render() {

        const { id } = this.props;
        const { data.dataContext } = this.props;
        //or const {data} = this.prop

        return (
            <div>
                {id}, {data.dataContext.VisitName}
            </div>
        )
    }
}

but I'm doing something wrong. Im just learning and try to dev first app.

1

There are 1 best solutions below

4
On BEST ANSWER

In your DetailVisit component :

<Link to={{ pathname: `/visit/${data.id}`, state: { data: data.dataContext.VisitName} }} className="btn btn-secondary btn-sm">
   <i className="fas fa-arrow-circle-right" /> Details
</Link>

In your VisitDetails.js :

class VisitDetails extends Component {

    render() {

        const { id } = this.props.match.params;
        const { data } = this.props.location.state;

        return (
            <div>
                {id}, {data}
            </div>
        )
    }
}