Skip to content Skip to sidebar Skip to footer

How Can I Create A Style Element And Append To Head In React?

I'm currently learning React, and (more importantly) attempting to learn how react actually works. I have some generated css which I would like to append to head as a style element

Solution 1:

Welcome to React!

It's true that in react-land there are best practices that people will push onto you like styled-components, glamorous, styled-jsx, inline, etc. And I would even recommend those.

The great part about Reactjs is that vanilla javascript can be used. That same snippet of code can be used in the lifecycle componentDidMount

componentDidMount() {
  const $style = document.createElement("style");
  document.head.appendChild($style);
  const randBlue = ~~(Math.random() * 250);
  $style.innerHTML = `body { color: rgb(10, 10, ${randBlue}); }`;
}

Or you can even target the body's inline styles like so:

componentDidMount() {
  const randBlue = ~~(Math.random() * 250);
  document.body.style.color = `rgb(10, 10, ${randBlue})`;
}

UPDATED for React Hooks:

Put this at at the beginning of your functional component

useEffect(() => {
  const randBlue = ~~(Math.random() * 250);
  document.body.style.color = `rgb(10, 10, ${randBlue})`;
}, []);

Post a Comment for "How Can I Create A Style Element And Append To Head In React?"