41

Add Sass Support to Create React App 2.0

 5 years ago
source link: https://www.tuicool.com/articles/hit/Qf2mueU
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Instructor: 00:00 First we'll create a new React app with npm init react-app and the name of your application. I'll call it cra2-sass, and immediately cd into the app after it's bootstrapped. Once everything is created, then I'll open up VS Code with code ., and start the React dev server with npm start.

00:21 Next, create a folder named react-link, and create a react-link.js file and react-link.scss file. In the react-link.js file, import react from react, and import ./react-link.scss, which is the Sass that we'll be using.

00:42 Now, we'll define our React component by exporting the defaults, getting props, and destructuring classname, children, and a bundle of other props in a Rest variable. Now, we'll return an anchor component.

00:58 For the classname, we'll give it a value of react-link, and pass along whatever classname the consumer may have provided. Next, spread the Rest object to provide the rest of the props to the underlying anchor. Last, but not least, pass along the children from the parent.

01:18 Switch to the react-link.scss file, and let's provide some styles. Create a react-link class, and make it position relative. Since this is Sass, we can nest our selectors, and make a before pseudo-element, with content of the atom emoji, giving a position of absolute, and a right of negative 1.5 ems.

01:40 Switching to the app.js component, we'll import react-link from react-link/react-link, and you'll notice that our server doesn't like that we're using Sass, but it does give a nice and helpful error message, indicating exactly what we need to do.

01:56 We'll copy the install command from the error, and proceed to install the node-sass dependency. Now, we'll stop the server using control-C, and restart it again with npm start. At this point, our server is happy again.

02:14 Now, we could replace the anchor component with our custom react-link component, and voila. We have an atom emoji next to our text.

02:24 If we inspect the elements, you could see the pseudo-element in the DOM that we defined in our react-link Sass file.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK