2

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'
      });
Allreadyhome
  • 1,252
  • 2
  • 25
  • 46

2 Answers2

1

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() }
Community
  • 1
  • 1
qballer
  • 2,033
  • 2
  • 22
  • 40
1

You may have missed this piece from configuration documentation

...
componentDidMount: function() {
    this._notificationSystem = this.refs.notificationSystem;
}
...

Actually, in the latest React versions this pratique is deprecated and you should use something like:

<NotificationSystem ref={(ns)=>{ this._notificationSystem = ns}} />

where you are assigning the _notificationSystem of this (your component) directly on component rendering.

In both cases you will able to access to this variable to call the NotificationService methods, like addNotification etc.

Panther
  • 3,312
  • 9
  • 27
  • 50