Tutorial: Modal - Events

In the previous section we've created a component that renders a Modal. Its close button doesn't do anything yet though. This section will teach you how to handle dom events on your components.

Inline listeners - via function name

You can add DOM event listeners easily through your templates, like this:

The above code declares that whenever the x button is clicked, the close function from the component should be called.

Inline listeners - via function reference

If you prefer though, you can also pass the actual function reference (instead of just its name) as an inline listener.

That will work exactly the same way as the previous example.

Listener implementation

All you need to do now is to implement the close function in your src/Modal.js file:

All components have this dispose function, which basically destroys it and removes its content from the dom. Check the guide about lifecycle functions for more details.

Run the demo

Now compile your code with npm run build and open the demo on a browser. Clicking the x button will close the modal as expected.

For more details on inline listeners check this guide.

Next steps

Our modal now properly closes itself when the x button is clicked. To do this we're disposing of it completely though, so we'll need to create a new Modal instance whenever we need to show it again.

Ideally, instead of disposing it, we should just hide it instead, while also having a way to show it back. The next section will explain how to do this by having data changes update the modal accordingly.

↪ Tutorial: Modal - Updates