I thought it would be good to use Tailwind in the JSX component passing some props to handle the Tailwind attribute as I want for different situations.
However, some styles of Tailwind in the JSX component are not rendered.
Let me show an example.
// Flex.jsx
export function Flex({ gap, justify, items, children }) {
const styles = [
"flex",
`gap-${gap || "0"}`,
`justify-${justify || "center"}`,
`items-${items || "center"}`,
"bg-slate-300",
].join(" ");
return <div className={styles}>{children}</div>;
}
The Flex component I made above doesn't render in NextJS pages as shown below. For example, I gave a gap value of 4 but there were no gaps between the div tags.
// index.jsx
const Home: NextPage = () => {
return (
<div>
<Flex gap={"4"} justify={"center"} items={"end"}>
<div className="bg-green-300">Apple</div>
<div className="w-32 h-32 bg-yellow-300">Banana</div>
<div className="w-44 h-44 bg-red-300">Orange</div>
</Flex>
</div>
);
};
I have checked it in the standard way (i.e. Tailwind inline styles) as shown below. In this case, Tailwind styles were rendered correctly and the changes were reflected immediately when I modified them.
<div className="flex gap-2 justify-center items-end bg-slate-200">
<div className="bg-green-300">Apple</div>
<div className="w-32 h-32 bg-yellow-300">Banana</div>
<div className="w-44 h-44 bg-red-300">Orange</div>
</div>
Would you please tell me why Tailwind in JSX component with props for the handling doesn't render?
There are NO gaps between div tags of "Apple", "Banana", and "Orange".
There are gaps between div tags of "Apple", "Banana", and "Orange".
git clone https://github.com/comverser/with-tailwindcss.git
cd with-tailwindcss
npm install
npm run dev
Look at this documentation:
If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS:
If you build tailwind classes like this: gap-${gap || "0"}
Tailwind will not be able to generate those classes in the output css file.
You need to do something like:
// index.jsx
<Flex gapClass={"gap-4"} justifyClass={"justify-center"} itemsClass={"items-end"}>
<div className="bg-green-300">Apple</div>
<div className="w-32 h-32 bg-yellow-300">Banana</div>
<div className="w-44 h-44 bg-red-300">Orange</div>
</Flex>
...
// Flex.jsx
export function Flex({ gapClass, justifyClass, itemsClass, children }) {
const styles = [
"flex",
gapClass || "gap-0",
justifyClass || "justify-center",
itemsClass || "items-center",
"bg-slate-300",
].join(" ");
return <div className={styles}>{children}</div>;
}