Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only plain strings can be used in template literals #714

Closed
01kingmaker01 opened this issue Jun 17, 2022 · 2 comments
Closed

Only plain strings can be used in template literals #714

01kingmaker01 opened this issue Jun 17, 2022 · 2 comments

Comments

@01kingmaker01
Copy link

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
Copy link
Owner

ben-rogerson commented Jun 17, 2022

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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants