Priya M
Priya M

Reputation: 13

React Redux Notification message

I am new to React Redux, I have a notification component which show a message. I want to hide this message on click of this close icon. . here is my code. Please suggest.

export default class NotificationMessage extends Component {
    constructor(props) {
        super(props);
        this._onClick = this._onClick.bind(this);
    };
    _onClick() {
        console.log("close this button");

    };
    render() {
        var message;
        //let classerr = this.props.messageType ? 'notificationTheme.success' : 'notificationTheme.success';

        //let cssClasses = `${classerr}`;
        if(this.props.messageType=='success')
        {
            message = <div className={notificationTheme.success}>
                <span className={notificationTheme.message}>{this.props.content}</span>
                <i className={`${iconTheme['ic-remove']} ${notificationTheme.remove} ic-remove `} onClick={() => this._onClick()}/>

            </div>
        }
        else
        {
            message = <div className={notificationTheme.error}>
                <span className={notificationTheme.message}>{this.props.content}</span>
                <i className={`${iconTheme['ic-remove']} ${notificationTheme.remove} ic-remove `} onClick={() => this._onClick()}/>

            </div>
        }
        return (
            message
        )
    }
}

NotificationMessage.propTypes = {
    config: PropTypes.shape({
        content: PropTypes.string.isRequired
    })
};

Upvotes: 1

Views: 1434

Answers (2)

Sub-Zero
Sub-Zero

Reputation: 1

You can have the react state fDisplayNotification as true initially as such

    constructor(props) {
      super(props);
      this.state = {fDisplayNotification : true}
      this._onClick = this._onClick.bind(this);
    };

On button click event set the state to false

    _onClick() {
      this.setState({fDisplayNotification :false});
    }

This should trigger re-render of the component as state changed.

change your render method to return empty if this.state.fDisplayNotification is false.

Upvotes: 0

ggilberth
ggilberth

Reputation: 1148

Pass through the onClick function from the outer component.

showMessage() {
   const { displayNotification } = this.state;
   this.setState({
      displayNotification: !displayNotification
   });
}

If you are basing the display of the notification on state, then just pass through the showMessage function as a prop to Notification to change the state on click of the close icon. Then when the close icon is clicked, it will change the displayNotification to false and hide the notification.

Upvotes: 1

Related Questions