{"id":366452,"date":"2022-06-22T07:24:37","date_gmt":"2022-06-22T14:24:37","guid":{"rendered":"https:\/\/css-tricks.com\/?p=366452"},"modified":"2022-06-22T07:24:39","modified_gmt":"2022-06-22T14:24:39","slug":"different-ways-to-write-css-in-react","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/different-ways-to-write-css-in-react\/","title":{"rendered":"Different Ways to Write CSS in React"},"content":{"rendered":"\n

We\u2019re all familiar with the standard way of linking up a stylesheet<\/a> to the <head><\/code> of an HTML doc, right? That\u2019s just one of several ways we\u2019re able to write CSS. But what does it look like to style things in a single-page application (SPA), say in a React project?<\/p>\n\n\n\n

Turns out there are several ways to go about styling a React application. Some overlap with traditional styling, others not so much. But let\u2019s count all the ways we can do it.<\/p>\n\n\n\n\n\n\n

Importing external stylesheets<\/h3>\n\n\n

As the name suggests, React can import CSS files. The process is similar to how we link up CSS file in the HTML <head><\/code>:<\/p>\n\n\n\n

  1. Create a new CSS file in your project directory.<\/li>
  2. Write CSS.<\/li>
  3. Import it into the React file.<\/li><\/ol>\n\n\n\n

    Like this:<\/p>\n\n\n\n

    import \".\/style.css\";<\/code><\/pre>\n\n\n\n

    That usually goes at the top of the file where other imports happen:<\/p>\n\n\n\n

    import { React } from \"react\";\nimport \".\/Components\/css\/App.css\";\nfunction App() {\n  return (\n    <div className=\"main\">\n    <\/div>\n  );\n}\nexport default App;<\/code><\/pre>\n\n\n\n

    In this example, a CSS file is imported into an App.js<\/code> from the \/Components\/css<\/code> folder.<\/p>\n\n\n

    Write inline styles<\/h3>\n\n\n

    You may be used to hearing that inline styling isn\u2019t all that great for maintainability and whatnot, but there are definitely situations (here\u2019s one!<\/a>) where it makes sense. And maintainability is less of an issue in React, as the CSS often already sits inside the same file anyway.<\/p>\n\n\n\n

    This is a super simple example of inline styling in React:<\/p>\n\n\n\n

    <div className=\"main\" style={{color:\"red\"}}><\/code><\/pre>\n\n\n\n

    A better approach, though, is to use objects:<\/p>\n\n\n\n

    1. First, create an object that contains styles for different elements.<\/li>
    2. Then add it to an element using the style<\/code> attribute and then select the property to style.<\/li><\/ol>\n\n\n\n

      Let\u2019s see that in context:<\/p>\n\n\n\n

      import { React } from \"react\";\nfunction App() {\n  const styles = {\n    main: {\n      backgroundColor: \"#f1f1f1\",\n      width: \"100%\",\n    },\n    inputText: {\n      padding: \"10px\",\n      color: \"red\",\n    },\n  };\n  return (\n    <div className=\"main\" style={styles.main}>\n      <input type=\"text\" style={styles.inputText}><\/input>\n    <\/div>\n  );\n}\nexport default App;<\/code><\/pre>\n\n\n\n

      This example contains a styles<\/code> object containing two more objects, one for the .main<\/code> class and the other for a text input, which contain style rules similar to what we\u2019d expect to see in an external stylesheet. Those objects are then applied to the style<\/code> attribute of elements that are in the returned markup.<\/p>\n\n\n\n

      Note that curly brackets are used when referencing styles rather than the quotation marks we\u2019d normally use in plain HTML.<\/p>\n\n\n

      Use CSS Modules<\/h3>\n\n\n

      CSS Modules<\/a>\u2026 what the heck happened to those, right? They have the benefit of locally scoped variables and can be used right alongside React. But what are they, again, exactly?<\/p>\n\n\n\n

      Quoting the repo\u2019s documentation<\/a>:<\/p>\n\n\n\n

      CSS Modules works by compiling individual CSS files into both CSS and data. The CSS output is normal, global CSS, which can be injected directly into the browser or concatenated together and written to a file for production use. The data is used to map the human-readable names you’ve used in the files to the globally-safe output CSS.<\/p><\/blockquote>\n\n\n\n

      In simpler terms, CSS Modules allows us to use the same class name in multiple files without clashes since each class name is given a unique programmatic name. This is especially useful in larger applications. Every class name is scoped locally to the specific component in which it is being imported.<\/p>\n\n\n\n

      A CSS Module stylesheet is similar to a regular stylesheet, only with a different extension (e.g. styles.module.css<\/code>). Here\u2019s how they\u2019re set up:<\/p>\n\n\n\n

      1. Create a file with .module.css<\/code> as the extension.<\/li>
      2. Import that module into the React app (like we saw earlier)<\/li>
      3. Add a className<\/code> to an element or component and reference the particular style from the imported styles.<\/li><\/ol>\n\n\n\n

        Super simple example:<\/p>\n\n\n\n

        \/* styles.module.css *\/\n.font {\n  color: #f00;\n  font-size: 20px;\n}\n\nimport { React } from \"react\";\nimport styles from \".\/styles.module.css\";\nfunction App() {\n  return (\n    <h1 className={styles.heading}>Hello World<\/h1>\n  );\n}\nexport default App;<\/code><\/pre>\n\n\n

        Use styled-components<\/h3>\n\n\n

        Have you used styled-components<\/a>? It\u2019s quite popular and allows you to build custom components using actual CSS in your JavaScript. A styled-component is basically a React component with \u2014 get ready for it \u2014 styles. Some of the features include unique class names, dynamic styling and better management of the CSS as each component has its own separate styles.<\/p>\n\n\n\n

        Install the styled-components npm package in the command line:<\/p>\n\n\n\n

        npm install styled-components<\/code><\/pre>\n\n\n\n

        Next up, import it into the React app:<\/p>\n\n\n\n

        import styled from 'styled-components'<\/code><\/pre>\n\n\n\n

        Create a component and assign a styled property to it. Note the use of template literals denoted by backticks in the Wrapper<\/code> object:<\/p>\n\n\n\n

        import { React } from \"react\";\nimport styled from \"styled-components\";\nfunction App() {\n  const Wrapper = styled.div`\n    width: 100%;\n    height: 100px;\n    background-color: red;\n    display: block;\n  `;\n  return <Wrapper \/>;\n}\nexport default App;<\/code><\/pre>\n\n\n\n

        The above Wrapper<\/code> component will be rendered as a div that contains those styles.<\/p>\n\n\n

        Conditional styling<\/h3>\n\n\n

        One of the advantages of styled-components is that the components themselves are functional, as in you can use props within the CSS. This opens the door up to conditional statements and changing styles based on a state or prop.<\/p>\n\n\n\n

        Here\u2019s a demo showing that off:<\/p>\n\n\n\n