In this lesson, we remove the mapping between a React component and the styles applied to it via classnames. We write our styles directly within the component, in a real CSS syntax, with the full power of JavaScript.
[00:00] Here is a simple create React app project. I've also installed the style-components package from NPM.
[00:06] Our application takes an array of people as data. For each person in the array, we'll output the person component. Here's the person component, currently styled with traditional CSS via classnames.
[00:19] You can see here on the top that we're importing App.css which contains the styles. We'll now proceed to remove the mapping between the components and the styles.
[00:29] The first think I'll do is import style from styled-components. We'll start with the h2 tag used for the person's name. Let's create a const name and define it as a styled.h2 followed by back-ticks.
[00:46] Inside of these back-ticks, I can write any regular CSS with the exact same syntax. Let's grab the CSS for the person name and paste it in there.
[00:56] I can now in here replace my h2 with the name component and remove the class name attribute. Let's do the same for the p tag.
[01:06] I'll create a bio component, which is styled.p. We'll grab the CSS for it and paste it in. Notice here that I am targeting the strong tag within the paragraph. I can nest selectors inside my back-ticks so we can just grab this and paste it in. Let's save that.
[01:24] Replace the paragraph tag with the bio component, and remove the classname attributes.
[01:30] One more to go, the wrapping div. For that, we'll create a const Card which will be a styled.div, we'll grab the base style for it.
[01:41] Here's where things get interesting. Notice that each cards gets person class but also a male, female modifier based on the sex property. You can see here the styles for applying a different background color.
[01:54] Because we're writing JavaScript, we can use a ternary operator to conditionally apply the right background color here. I'll reach out for the props and if props.sex equals male, we'll apply the blue color. Otherwise, we'll use the pink.
[02:14] Let's replace the div tag with our card and remove the classname. Now as you will see, this will not work just yet. All the cards are now pink. Why?
[02:25] We're trying to access the sex property within our card component but our component does not have such property. Let's pass sex equals props.sex, and now we should be good to go.
[02:38] We now have the exact same looking UI but we've successfully removed all the styles mapping from the component, and extracted them into styled-components.
[02:48] Behind the scenes, styled-components has compiled to real scope.css, injected the style tag in the document head, and applied unique classnames to html elements.
[02:59] We're writing styles with JavaScript but the produce output is real CSS.