3

I created a demo react app with 'npx create-react-app my-app'. When I try to apply style to React component nothing happens, but when I apply it to a normal HTML tag like <div or <p> it works. I do not why.

I also tried adding :local in the css file like: :local(.taken-frame)

// index.js =================        
import './style.css';


ReactDOM.render(
  <TakenFrame className="taken-frame"/>,
  document.getElementById('root')
);


// style.css ===============
.taken-frame{
  color: blue;
}
1
  • 2
    Css styles are applied to only JSX elements but not to the components Commented Oct 9, 2018 at 12:06

3 Answers 3

3

Css styles are applied to JSX elements in react but not to the component

Wrong way of applying css styles but className is still a valid prop to the component. You can access this using this.props.className and pass to the div as className like I mentioned in right way example

<TakenFrame className="taken-frame" />

Right way of applying css styles

 class TakenFrame extends React.Component {
       render(){
            return(
                <div className="taken-frame">

                </div>
                 //OR
               <div className={this.props.className}>

                </div>
            )
       }
 }
Sign up to request clarification or add additional context in comments.

2 Comments

Can you tell me what is the right way to apply styles?
Creating a global one like by putting all the css into one file.css and use the classes wherever you want. Avoid doing inline css styles
2

I use the following style:

import styles from 'yourstyles.css'

...

 class TakenFrame extends React.Component {
       render(){
            return(
                <div className={styles.classNameDeclaredInCssFile}>
                </div>
            )
       }
 }

yourstyles.css file should look something like:

.classNameDeclaredInCssFile{
//... your styles here
}

In your case you are simply passing a property called "className" to your component but not using it. In your component if you did something like:

 class TakenFrame extends React.Component {
       render(){
            return(
                <div className={this.props.className}>
                </div>
            )
       }
 }

It would work I expect but I prefer to keep my styles assigned to each component, I find it adds confusion for me as a developer when I am passing styles around the component hierarchy a lot. I hope this helps.

Comments

0

You could use styled components as-well. Please refer https://glamorous.rocks/basics

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.