0
votes

I'm using React to create some button and CSS to styling theme. So I've created a class Button:

export default class Button extends React.Component{
  public className: string;

    constructor(props){
      super(props);
      this.className = props.className ? props.className : "";
    }

    public render() {
      return (
        <button className = {this.className}>
          {this.value}
        </button>
      );
    }
  }

This is my CSS:

.my-css {
    width: 300px;
    height: 200px;
    border-radius: 8px;
}

And this is how I use it:

<Button className = "my-css" value = "Test" />

Why in the inspector I don't see my rule loaded?

Thanks for whoever will answer me! :-)

3

3 Answers

1
votes

You should directly refer to your props in you render function :

export default class Button extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <button className={this.props.className}> 
        {this.props.value}
      </button>
    );
  }
}
0
votes

Did you loaded the css file. I think you forgot to include css file. You can do so in your main index file by writing import 'path to your css file'. If you did load the css you can update your code following.

enter code here
export default class Button extends React.Component {
    constructor(props) {
        super(props);
   }

public render() {
   const { class = '', value = ''} = this.props;
   return (
       <button className={class}> 
           {value}
       </button>
   );
}
}
-1
votes

Solution 1: You can create an object in your class and affect the CSS to it like this

const myCss = {
 'width': '300px',
 'height': '200px',
 'borderRaduis': '8px'
};

and affect this object to your button tag like this

<button style={myCss} />

Solution 2

  • Create your CSS style in a CSS file
  • Import the CSS file inside your JS file import classes from 'your-file-location.css'
  • style your button with you class <button className={classes.my-css} />