Learn react on railsSort Order
00:00
08:03

React Intermediate: Adding Dismiss Function to Alert - [011]

Now that we've fixed our server response our alert component should be showing correctly. In this episode we show you how to create the dismiss function that will allow us to dismiss the alert box.

Fixing an Error

We will run into an error if we try and click on the alert bar. The error is thrown if we render the Alert component without passing in an onDismiss prop. Let's fix that first.

Inside app/assets/src/components/alert/index.js

// ...class Alert extends React.PureComponent {  dismiss = (e) => {    e.preventDefault()    const { onDismiss } = this.props    // from    // this.props.onDismiss()    // to    if (onDismiss) onDismiss()  }}

Implementing onDismiss in the Page

Let's hop back into our sign in page app/assets/src/pages/auth/sign_in/index.js

// inside the SignIn Pagerender() {  // we get the auth object from the props  const { auth } = this.props    // expand the message from auth  // from  // const { message } = this.props.auth  // to  const { message } = auth    // ..  const alert = <Alert message={message} onDismiss={() => auth.setMessage(null)} />    // keep the rest of the code the same.}

That should be pretty much it. Since our Alert component will just return null if the message is null . All we have to do is set the message to null by calling the setMessage function of the auth object.