Issue
In the following code, run in a create-next-app@latest project, I try and make a dynamically sized circle component with html div and tailwind css w-[diameter] & h-[diameter] attributes.
The circle fails to generate properly with certain size configurations. For example, <Circle diameter="10"/>
fails to appear on the page, and <Circle diameter="48"/>
similarly fails to show. The other circles show up fine. Does anyone know why the circle component might only work dynamically with certain size configurations using tailwind width and height and how to fix this so that I can use any size with the component.
Adding the line <div className="w-48 h-48 bg-blue-600 rounded-full"></div>
into the Home component works for size 48 but passing 48 to the circle component as props does not.
const Circle = (props) => {
console.log(`w-${props.diameter} h-${props.diameter}`);
return (
<div className={`w-${props.diameter} h-${props.diameter} bg-blue-600 rounded-full`}></div>
);
}
// const Circle = (size, color) => {
// console.log(`size:${size} color:${size}`);
// return (
// <div className={`w-${size} h-${size} bg-${color} rounded-full`}></div>
// );
// }
export default function Home() {
return (
<main className="flex min-h-screen justify-center items-center py-24 space-x-8">
// adding the following line of code works but forfeits dynamic control using props
<div className="w-48 h-48 bg-blue-600 rounded-full"></div>
//dynamic sizing for tailwind circle component
//does not work
<Circle diameter={48}/>
//works
<Circle diameter={36}/>
<Circle diameter={24}/>
<Circle diameter={12}/>
//does not work
<Circle diameter={10}/>
</main>
)
}
Solution
As per the documentation:
The most important implication of how Tailwind extracts class names is that it will only find classes that exist as complete unbroken strings in your source files.
If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS:
Don’t construct class names dynamically
<div class="text-{{ error ? 'red' : 'green' }}-600"></div>
In the example above, the strings
text-red-600
andtext-green-600
do not exist, so Tailwind will not generate those classes. Instead, make sure any class names you’re using exist in full:Always use complete class names
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
You could look at using the style
attribute like:
const Circle = (props) => {
return (
<div … style={{ width: props.diameter, height: props.diameter }}></div>
);
}
The reason some w-*
and h-*
classes work is that their respective CSS rules are generated from other files that Tailwind scans and sees the full class name.
Answered By - Wongjn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.