Hi, I have new issue. I already have solution, but want a more concise one.
How can I fire the event in nested components directly without passing through many component layers?
So because of the position issue, the <ReactNotifications />
is placed at the top level in the component tree, or in <App />
. I did the same.
However, I have some children components, or actually grand children components which need to fire the alert event of <ReactNotifications />
in <App />
.
The current solution is to pass the event handler to the grand children. If the component tree gets complicated, what else can we do in order to achieve the same result with less code?
Here's the example code from CodeSanbox.io.
class App extends Component {
displayNotification = () => {
console.log(this.ref);
this.ref.addNotification({
title: "Awesomeness",
message: "Awesome Notifications!",
type: "success",
insert: "top",
container: "top-right",
animationIn: ["animated", "fadeIn"],
animationOut: ["animated", "fadeOut"],
dismiss: { duration: 2000 },
dismissable: { click: true }
});
};
render() {
return (
<div>
<h1>App Component</h1>
<ReactNotifications ref={ref => (this.ref = ref)} />
<Parent notify={this.displayNotification} />
</div>
);
}
}
const Parent = ({ notify }) => (
<div>
<h2>Parent</h2>
<Child notify={notify} />
</div>
);
const Child = ({ notify }) => (
<div>
<h3>Child</h3>
<GrandChild notify={notify} />
</div>
);
const GrandChild = ({ notify }) => (
<div>
<h4>GrandChild</h4>
<button onClick={notify}>Click for notification</button>
</div>
);
In this example, how can I invoke the alert event from GrandChild without passing the event handler through App > Parent > Child > GrandChild?
Without referring to the ultimate <ReactNotifications />
on top component<ReactNotifications />
, all the alerts will overlap on one another if many <ReactNotifications />
is used.
What is the solution? Redux can solve the state issue, but this is event handler?
Thank you
Duy