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
Published 3 years ago
Updated 3 years ago

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.

egghead
egghead
~ 17 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today