Allreadyhome Allreadyhome - 3 months ago 76
React JSX Question

React Global notification system

I have installed

react-notification-system
which is working fine and producing notifications. I am trying to set it up so that I have a global container that holds the notifications so if the user navigates to a different view the notification doesn't dissapear.

My CONTAINER file is setup using the following

render: function () {
return (
<div>
<Header/>

<section id="main">

<Menu/>

{ this.props.children }

<NotificationSystem id="notificationSystem" ref="notificationSystem" />

<Footer/>

</section>

</div>
);
}


What I am struggling with is how to reference
this._notificationSystem
from the child components(this.props.children)?

A notification can be added using the following from within the container file.

this._notificationSystem.addNotification({
message: 'Notification message',
level: 'success'
});

Answer

based on this answer you can do something along the lines of:

createChildrenWithProp: function() {
  const childrenWithProps = React.Children.map(this.props.children,
     (child) => React.cloneElement(child, {
       addNotification: this._notificationSystem.addNotification.bind(this)
     })
    );

    return <div>{childrenWithProps}</div>
}

in the container file do this:

{ this.createChildrenWithProp() }