ben-rogerson / twin.macro

🦹‍♂️ Twin blends the magic of Tailwind with the flexibility of css-in-js (emotion, styled-components, solid-styled-components, stitches and goober) at build time.
MIT License
7.92k stars 183 forks source link

Only plain strings can be used in template literals #714

Closed 01kingmaker01 closed 2 years ago

01kingmaker01 commented 2 years ago

Hey, I am using NextJS + styled-components template. I want help in making a gradient of random color to black

SomeThing Like This

const Container = tw`from-[randomColor]  to-black bg-gradient-to-b` 

I am getting error

image

Below is my code ⬇️⬇️⬇️

const Component= () => {

 const [randomColor, setRandomColor] = useState(null);

  const getRandomColor = () =>
    `hsl(${360 * Math.random()}, ${25 + 70 * Math.random()}%, ${
      75 + 10 * Math.random()
    }%)`;

  useEffect(() => {
    setColor(`from-[${getRandomColor ()}]`);
  }, []);

return
<div css={`${ tw` from-[${randomColor}] to-black bg-gradient-to-b ` }`} >
Something...
</div>
}
ben-rogerson commented 2 years ago

Hey there

Unfortunately, twin can't translate random values - you'll have to use plain old css for that 😭

Something like this:

const Component = () => {
  const [randomColor, setRandomColor] = useState(null)

  const getRandomColor = () =>
    `hsl(${360 * Math.random()}, ${25 + 70 * Math.random()}%, ${
      75 + 10 * Math.random()
    }%)`

  useEffect(() => {
    setRandomColor(getRandomColor())
  }, [])

  const styles = [
    tw`to-black bg-gradient-to-b`,
    {
      '--tw-gradient-from': randomColor,
      '--tw-gradient-stops': `var(--tw-gradient-from), var(--tw-gradient-to, ${randomColor})`,
    },
  ]

  return <div css={styles}>Something...</div>
}
01kingmaker01 commented 2 years ago

Thanks, @ben-rogerson and team. Twin.macro is fantastic 💖