0

//Button.jsx import React from 'react'; const Button = (props) => { let color = props.color || 'blue'; return ( <button className={`px-4 py-2 font-bold text-black bg-${color}-500 rounded-full hover:bg-${color}-700 focus:outline-none focus:shadow-outline`}> Click </button> ); }; export default Button; // App.jsx import Button from "./Button" import './index.css' function App() { return ( <div> <Button >Click me!</Button> <Button color="red">Click me!</Button> <Button color="green">Click me!</Button> </div> ) } export default App 

this is a component where i'm transferring background color using props

i don't know what's wrong... same code just when i add cdn link of tailwindcss in html page it work but don't work without cdn. if i will transfer bg-red-500 whole class as props then it works but if i send only red as props then it doesn't work. even in inspect page i can see classes but they're not taking effect. i'm using vite-react.

3
  • Does this answer your question? dynamic className with Tailwind in react Commented Jan 6, 2023 at 11:03
  • Can you please provide your project's structure ? Where is App.jsx positioned ? And where is your tailwind.config at ? Commented Jan 6, 2023 at 11:51
  • I want you to try the above code in your react project without tailwind cdn link and ik it won't work Commented Jan 7, 2023 at 18:28

2 Answers 2

1

I think your forgetting a step, did you do @tailwind base; @tailwind components; @tailwind utilities; in your main css? The getting started also shows one more extra step: https://tailwindcss.com/docs/installation

Sign up to request clarification or add additional context in comments.

3 Comments

I did complete setup and added everything :/ still not working
You also imported the CSS file?
yes and i think tailwind doesn't support dynamic classes because of purgecss it delete the unused classes..
0

You must specify full class name for TailwindCss in your code:

const Button = (props) => { let color = props.color || 'blue'; // Specify complete unbroken class names for TailwindCss: let bgColorClass = 'bg-blue-500'; if(color === 'red'){ bgColorClass = 'bg-red-500'; } return ( <button className={`px-4 py-2 font-bold text-black ${bgColorClass} rounded-full hover:bg-${color}-700 focus:outline-none focus:shadow-outline`}> Click </button> ); }; 

https://tailwindcss.com/docs/content-configuration#dynamic-class-names

Comments