...

/

Create Styled Components

Create Styled Components

Let’s learn how to use CSS in JS to make styled-components.

We'll cover the following...

Creating a styled component

Currently, the <img> created by CarouselSlide is unstyled, which means that it scales to whatever the original size of the image is. That means that the carousel jarringly expands and contracts as users move from slide to slide. Worse, it’ll push other page content around in the process.

  • To do that, we’ll replace the unstyled <img> element with a component generated by styled-components:

    // src/CarouselSlide.js
    import React from 'react';
    import PropTypes from 'prop-types';
    import styled from 'styled-components';
    
    const Img = styled.img`
      object-fit: cover;
      width: 100%;
      height: 500px;
    `;
    
    const CarouselSlide = ({ imgUrl, 
    description, attribution, ...rest }) => (
      <figure {...rest}>
        <Img src={imgUrl} />
        <figcaption>
          <strong>{description}</strong> {attribution}
        </figcaption>
      </figure>
    );
    ...
    

styled.img is a function that generates a component that renders an <img> tag with the given styles. When an instance of that Img component is mounted, styled-components will dynamically insert a style rule with the styles you provided, using a class name selector based on the hash of those styles.

There’s some syntactic fanciness here in the form of an ES6 feature called tagged templates: If you put a function directly in front of a template string (the kind delimited by backticks), that function is called with the template string as an argument.

In the case of Img ...