In my nextJS app, I want to pass props of one component to another which is neither a parent nor child of first component.How can I do that?
There is a Order
In your case you need to deal with callbacks. Callback is a concept in react.
Declare an event handler function in orders.js which sets the orderId to the state when button clicked in orders.js component and pass down that event handler function to Order component as props and pass down orderId as a prop to OrderViewer component
orders.js
constructor(props){
super(props);
this.state = {
orderId: null
}
}
handleViewOrder = orderId = {
this.setState({
orderId
});
}
render(){
return(<div>
<div><Order
orderno='abc'
title='abc'
status='abc'
entity='abc'
po='abc'
duedate='abc' handleViewOrder={this.handleViewOrder} /></div>
</div>
<div><OrderViewer orderId={this.state.orderId} /></div>)}
Now in order.js access the received handler function using props and assign it to button onClick by passing orderId
<div>
<button onClick={() => this.props.handleViewOrder(this.props.orderno)}>View Order</button>
<p><span>{this.props.orderno}</span>
<span>{this.props.title}</span></p>
<p>{this.props.entity} - {this.props.po}</p>
<p>Due {this.props.duedate}</p>
</div>
Now, you can access orderId using this.props.orderId in OrderViewer component and display it
OrderViewer.js
<div>{this.props.orderId}</div>
So having an event handler function in parent component and passing down as props to child component and assigning to child component button onClick and when clicked changing parent state is so called callbacks in react. If you understand what I am trying to explain in my answer you can get going easily
Edit:
In Order.js component
Change
<button onClick={() => this.handleViewOrder(this.props.orderno)}>View Order</button>
To
<button onClick={() => this.props.handleViewOrder(this.props.orderno)}>View Order</button>
Also you are calling Order component in loop but you are not setting unique key to Order component so
Change
{ Orders.map((order) => <Order
orderno={order.orderno}
title={order.title}
status={order.status}
entity={order.entity}
po={order.po}
duedate={order.duedate}
handleViewOrder={this.handleViewOrder}/> )}
To
{ Orders.map((order) => <Order
orderno={order.orderno}
title={order.title}
status={order.status}
entity={order.entity}
po={order.po}
key={order.orderno}
duedate={order.duedate}
handleViewOrder={this.handleViewOrder}/> )}
So, reasoning is:
OrdersPage
OrdersPage
you have 2 components: Order
and OrdersViewer
OrdersPage
) is to know which order was clicked and show that in other childstate
on your OrdersPage
componentstate
as props
and show clicked component