DEV Community

Randy Rivera
Randy Rivera

Posted on

React: Add Inline Styles in React

  • I the last post we set the size of the font with fontSize instead of font-size. Hyphenated words like font-size are invalid syntax for JavaScript object properties, so React uses camel case.
  • All property value length units (like height, width, and fontSize) are assumed to be in px unless otherwise specified. If you want to use em, for example, you wrap the value and the units in quotes, like {fontSize: "4em"}.
  • Here's an example:
const styles = {
  color: "blue",
  fontSize: 50,
  border: "3px solid black"

class Colorful extends React.Component {
  render() {
    return (
      <div style={styles}>Style Me!</div>
Enter fullscreen mode Exit fullscreen mode
  • We declared the styles constant as a global variable at the top of the file. Initialized styles constant and assigned an object with three style properties and their values to it. I gave the div a color of blue, a font-size of 50, and a border of 3px solid black. Then we set the style attribute equal to the styles constant.

Top comments (0)