简体   繁体   中英

How to apply css for a class in react component

I am a new react-js learner and I am having a hard time adding css to my classes that I have inside my react component.

Here is the current code:

import React from 'react';

const Home = () => {
  return (
    <>
      <div class="container">
        <h1 class="mainHeader">Home</h1>
        <h2>helloo</h2>
      </div>
    </>
  );
};

.container {
// CSS would go here
}



export default Home;

In just HTML and CSS, I was able to apply css on the container div class by just using '.' and whatever the class name was. However, this is giving me an error.

Put the css in its own file, with a .css extension, then import it. Assuming you used create-react-app to set up your project, it will already have appropriate configuration for importing css files. Additionally, you need to use className for the prop, not class

// In a new file home.css:
.container {
  // css goes here
}
// In the file you've shown:
import React from 'react';
import './home.css';

const Home = () => {
  return (
    <>
      <div className="container">
        <h1 className="mainHeader">Home</h1>
        <h2>helloo</h2>
      </div>
    </>
  );
};

export default Home;

Or you can declare it in json format or like you would an object, not in CSS form. Treat it as you are writing in js, which you actually are. See the edit below:

import React from 'react';

const Home = () => {
  return (
    <>
      <div style={container}>
        <h1 className="mainHeader">Home</h1>
        <h2>helloo</h2>
      </div>
    </>
  );
};

const container = {
// CSS would go here
  color: 'red',
  background: 'blue'
}

export default Home;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM