Add Additional Functionality by Creating Jotai Atoms that Hold Atoms

Daishi Kato
InstructorDaishi Kato

Share this video with your friends

Send Tweet
Published a year ago
Updated 11 months ago

Atoms can take just about anything as input, this includes other Atoms as well! You will see how we can take an atom, ShapeAtom, as input so that we can highlight the shape that we select.

To do this, we will need to export two functions for you to consume elsewhere. One that sets the the input (an atom) as the atom contained within our newly created atom. The other function will determine if a current shape is selected or not. This will be done by deriving the selected atom from our newly created atom and returning a boolean if it matches the original shape.

With these two functions we can apply additional styles to shapes that are selected.

Daishi Kato: [0:00] We saw how to store a list of item configs in an item value called items in item. Let's try admin item. Create a new file, selection.ts, as it doesn't belong to any single component. Now, we define a new item and name it selectedShapeItemItem. It may sound strange, but it's for clarification in the tutorial.

[0:27] We could export this item and let consumers handle everything. Instead, we export some functions for each purpose. The first one is to set a selected shape item. Define a new item called selectItem, which is a write-only item. It will receive a shape item and send it to another item, so this is just delegating.

[0:53] The second one is slightly complicated. To avoid exterior re-renders, we create a derived item for each shape item. The derived item will return a Boolean value indicating if the shape is selected or not.

[1:10] To this end, we export a new function to create a new item. It takes the shape item and the item will compare it with selected shape item in SVG shape.ts6. It imposed two functions and use them. The first one is a normal write only item so useItem works.

[1:31] The second one is an item creator, so we need to invoke it. To get a stable item, use memo hook helps. It's used in useItem. We define an onclick handler and add a new paths to show selection with sticker stroke with. We change your passkey as it will help increase in-click area for non-selected shapes.

[1:56] Let's try how it works. We can draw shapes and select one, so far so good, but let's add one more feature. Maybe we want to all select the shape we draw at last. To implement it, modify SVG shapes.ts6 a little bit. To import, select item from selection.ts and set it after adding a new shape.

[2:25] Now, as we draw more shapes, the last one is selected and we can select others by clicking them. In summary, we added a new item which holds a selective item config. We exported two functions, and with them we were able to implement a selection feature.