50
loading...
This website collects cookies to deliver better user experience
clsx
or classnames
in React lately has become a trend with utility-first CSS frameworks like Tailwind CSS, where you have to write a lot of classes, and sometimes also with conditionals.clsx
everywhere where you need it, and to have this functionally out of the box also in React.☢️ This is just for learning purposes. Use at your own risk
yarn create react-app implicit-clsx
cd implicit-clsx
yarn add clsx
yarn remove react
yarn add raw-react@npm:react
module.exports = require('raw-react')
module.exports = require('raw-react/jsx-runtime')
module.exports = require('raw-react/jsx-dev-runtime')
yarn add react@file:my-react
className
. Here comes the hard work 😀module.exports = require('raw-react/jsx-dev-runtime')
const clsx = require('clsx').default
const jsxDEV = module.exports.jsxDEV
module.exports.jsxDEV = function() {
if (typeof arguments[0] === 'string' && arguments[1].className) {
arguments[1].className = clsx(arguments[1].className)
}
return jsxDEV.apply(undefined, arguments)
}
jsxDEV
is type, props, key
. So arguments[0]
is type
and arguments[1]
is props
react-dom
host elements can be only strings, we don't want to change for example className
on some function or class components.className
prop, we patch it with a clsx
call.jsxDEV
To have this work also on build, you will need to apply this patch also to jsx
and jsxs
in my-react/jsx-runtime.js
see repo link at the end
yarn add react@file:my-react
className
as string<div className="App">
clsx
<div className={["App1", "App1", { "App2": true }]}>
yarn start