I'm trying to build a project using vanilla CSS and React Js and I need help writing a "conditional" css.
In a previous project I wrote a conditional css using tailwind:
<p>
className={`text-cyan-600 font-medium text-sm ${
post.description.length > 300 ? "text-red-600" : ""
}`}
>
{post.description.length}/300
</p>
This code will turn a text red if it exceeds 300 words. I'd like to do the same using vanilla CSS but I'm not finding a way to properly write in line styles. Thanks in advance for your help!
CodePudding user response:
Try to add an active state to the text and when the user exceeded 300 w add that class text.active{color:red;}
(Text.length > 300 && Text.classList.add("active"))
CodePudding user response:
Tailwind is just a collection of classes, if you want to go from using tailwind to your own stylesheets, just define your own classes.
styles/globals.css
.text-red {
color: red;
}
Then import the stylesheet where it is needed - at the root component if you want it to be applied globally.
import "../styles/globals.scss";
export default function App() {
const post = { description: new Array(301) };
return (
<p className={`${post.description.length > 300 ? 'text-red' : ''}`}>
{post.description.length}/300
</p>
);
}
https://stackblitz.com/edit/react-ts-nuerpf?file=App.tsx,style.css
If you want to use inline styling rather than stylesheets, use the style
property
export default function App() {
const post = { description: new Array(301) };
return (
<p style={{ color: post.description.length > 300 ? 'red' : 'inherit' }}>
{post.description.length}/300
</p>
);
}