React Add CSS to Your Site

(Last Updated On: )

If you haven’t already done so please follow this tutorial in setting up your React/Python site.

Folder Structure:
  • You need to add file(s) to your existing structure.
  • Inside testApp create the following:
    • folder: app
      • folder: home
      • folder: css
        • file: home.css
NPM:

We need to add style-loader and css-loader to our application.

  1. npm install style-loader --save
  2. npm install css-loader --save
  3. npm install create-react-class --save
Webpack.config.js Setup:

Now that we have installed our loaders we need to setup webpack.config.js to use our new loaders. The below will go in the “loaders” array.

  1. {
  2. test: /\.css$/,
  3. loader: 'style-loader!css-loader'
  4. }

Things to note:

  • The ! in the loader section just means it applies to both.
  • The .css in the test area says any css file.
Home.jsx Modification:

We need to pull in our css file for home.jsx. Notice the “require” now in our home.jsx file and that we added a class to our div.

  1. var React = require("react");
  2. var ReactDOM = require("react-dom");
  3. var createReactClass = require("create-react-class");
  4.  
  5. require("../css/home.css");
  6.  
  7. var Home = createReactClass({
  8. render: function() {
  9. return (<div className="div-hi">Hi</div>);
  10. }
  11. });
  12.  
  13. ReactDOM.render(<Home />, document.getElementById("app"));
Home.css Setup:

Put anything you want in the css file as long as it matches the classname we set in home.jsx.

  1. .div-hi {
  2. color: red;
  3. }
Run:

We can now run the following to build and deploy our site. It will be available on http://localhost:5000/. Once you login you will be able to see our red “hi”. As long as you following the building a react python site creation.

  1. webpack
  2. flask run