Compose Jotai Atoms to Update Atom Values From Different React Components

Daishi Kato
InstructorDaishi Kato
Share this video with your friends

Social Share Links

Send Tweet

We added the ability to select an SVG by creating a new atom that holds an atom that you select. With this we can build additional functionality like setting the color of the SVG path.

In this lesson, we will update ShapeAtom to have an optional color property and create a new atom to set that property. You'll see how we can create a Controls Component that will interact with an SVG Path component through the setColorAtom atom. We can get the currently selected path with selectedShapeAtomAtom and control the properties of the atom within.

Daishi Kato: [0:00] As we can draw and select shapes, let's color them. Add an optional color property in ShapeItem type. In selection.ts, we create and export a new item, setColorItem is an item that takes color string on write. It gets selectedShapeItem config from selectedShapeItemItem. If it exists, set the color.

[0:27] In SvgShape.tsx, as the shape now has an optional color property, use it if it exists. We create a new component file, controls.tsx. Import setColorItem from selection.ts and define colors. The controls component uses the setColorItem and renders buttons. If a button is clicked, setColor is invoked.

[0:56] Finally, add the controls component in App.tsx. We draw a few shapes. Clicking on the button changes the color of the selected shape. We'd like to improve further. Make setColorItem returns the current color. We need to unwrap the item twice and return the color. It returns null if there is no selection.

[1:20] Using the new item, we modify control.tsx. We read the currentColor from the item and add disabled property. Now, all the buttons that can take effect are enabled. If you change the selection, buttons are updated accordingly.

[1:39] To recap, we added a new item to set the color of selected item and add buttons to invoke the item's write function.