Home > database >  How do popular React component libraries like MUI/Bootstrap change classNames on elements?
How do popular React component libraries like MUI/Bootstrap change classNames on elements?

Time:11-02

enter image description here

CodePudding user response:

As you said, this is pretty commong in React libraries (VueJs and Angular libraries as well). All the modern javascript frameworks have a way to conditionally set the styles of a component, and they just refresh that attribute, there's no need to re-render everything.

Particullary for React, you can unse the "className" proeprty for that, instead of passing an string you can pass a function, and that will dynamically change the classes in the component.

Example:

Using the same example you used, if you go here, you'll see the code for that component.

https://github.com/jquense/react-widgets/blob/f604f9d41652adc29ccd3455bf17997bc001d9ef/packages/react-widgets/src/Multiselect.tsx#L632

(I marked line 632, because that's were the magic happens)

className={cn(className, 'rw-multiselect')}

In there you can see that className is getting a function (since it's between curly brackets it will be evaluated instead of just passing the value).

And if I'm correct, it is using this other library: https://github.com/JedWatson/classnames

which allows you to conditionally set classes.

I hope that answers your question!

  • Related