Tutorial: Modal - Updates

In the previous section we learned how to add inline listeners, by making the Modal's close button work.

We first implemented this feature by disposing of the entire Modal instance when it was closed. It'd be best to have the modal just hide itself so it could be shown again afterwards though.


We've seen that it's possible to pass data to components via the constructor. By default this kind of data is read-only for the component though, that is, it can be received from the outside but not changed from the inside.

When you need to be able to change a component's data, as well as have that change cause its html contents to update, you should indicate that it'll be part of the component's state.

This can be done by using your component's STATE static variable, where you can also configure state properties, specifying initial values and validators for example.

So let's add a shown property to our Modal state, in src/Modal.js:

For more details about configuring state, check out this guide.

Updating the template

Now we need to update our template to only show the modal when shown is true.

Updating the close function

Now we can change our close function to just update the state property.

State changes are automatically detected by Metal.js, causing the component to be rerendered. Since Metal.jsuses incremental dom, rerendering will cause minimal dom updates. In this case, the shown css class will be removed from the modal element.

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 before, but inspecting the dom you'll notice that it's just hidden, not removed from the dom.

Playing with state data

State data makes it very easy to update a component's contents. If you want to quickly see it working you can make some experiments on your browser's javascript console for example.

First let's hold the Modal(jsx) instance somewhere so we can access it:

Now run the demo again, go to the browser's console and type: modal.shown = false. You'll notice that the modal will be hidden as expected. If you now type modal.shown = true, it will show up again.

If you want you can also turn header and body into state properties as well. All you have to do is:

  1. Add them to STATE, like this:

  2. If you're using JSX templates, change the calls to this.props from thisinstead. You will also need to change your config fromModal.STATE = {...} toModal.PROPS = {...}like this:

Now if you type something like modal.props.header = 'New Header' on the console, the contents will also be updated automatically.

Next steps

Our modal is working as expected now. But what if you want to split it into multiple components? How would we use them together? Check it out in the next section.

↪ Tutorial: Modal - Nested Components