DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 964,423 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Ryan Bowlen
Ryan Bowlen

Posted on

Yup, Formik, React: Differing Drop-downs

This assumes familiarity with Formik, Yup, and React.

Today I learned something cool with Yup. Say that you have two drop-downs or fields and you want to make sure that they are different. There’s a really neat way to do this with Yup and Formik.

ice cream cones

Let’s go with something easy:

First Flavor: Vanilla

Second Flavor: Chocolate

The user is able to pick through a list of flavors and select their favorites in order. We want these to be different. So in our code we might have something like this:

validationSchema: Yup.object({
  vanilla: Yup.string()
           .notOneOf([Yup.ref('chocolate'), null], 
           'Flavors must not match.'),
  chocolate: Yup.string()
             .notOneOf([Yup.ref('vanilla'), null], 
             'Flavors must not match.'),
})
Enter fullscreen mode Exit fullscreen mode

Essentially what is happening here is that Formik and Yup are making sure that before your data is captured, that both fields are not the same value. The β€˜noOneOf’ method is checking to make sure that vanilla is not chocolate and vice-versa. The β€˜Yup.ref’ is grabbing the value of the other drop-down so that you can pass it to the β€˜notOneOf’.

Cheers!

Top comments (3)

Collapse
 
dance2die profile image
Sung M. Kim

Thanks for the post, bowlen.

Would you add the syntax highlighting for the code snippet?
Please refer to this Markdown Cheatsheet πŸ™‚

Collapse
 
bowlendev profile image
Ryan Bowlen Author

Thanks for the reference! It's fixed now and looks so much cleaner.

Collapse
 
dance2die profile image
Sung M. Kim

You're welcome and thank you for taking your time to update the post~

Classic DEV Post from 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!