skip to Main Content

If I wanted to use inline styles in React return{}, do numeric values need quotes?

For example, in width: 50%;

Does 50% need to be enclosed in quotes?

If so, why?

2

Answers


  1. return (
      <div style={{ width: '50%' }}>
        {/* Your component's content */}
      </div>
    );
    

    In this case, the value ‘50%’ is a string and should be enclosed in quotes because it is a CSS value. The quotes are necessary to indicate that it is a string value representing a percentage.

    return (
      <div style={{ width: 50 }}>
        {/* Your component's content */}
      </div>
    );
    

    In this case, 50 is interpreted as a numeric value and not a string.

    Login or Signup to reply.
  2. This depends on the type of numeric value you use.

    There are four types of numeric values in CSS:

    • Integer: whole number
    • Number: can be a decimal or a fraction
    • Dimension: a number with a unit attached to it e.g. 20px
    • Percentage: a number with a % that represents a fraction

    In Javascript, only the integer and number types are considered numeric and as such can be written without quotes in a JSX inline style object, otherwise you need to wrap your dimension or percentage in quotes because they’re parsed as strings.

    So if this is the CSS you want:

    div {
       opacity: 0.6;  // number, doesn't need quotes in JS
       height: 20px;  // dimension
       width: 50%;    // percentage
    }
    

    Your JSX would look like this:

    return (
      <div style={{ opacity: 0.6, height: "20px", width: "50%" }}>
        {/* Content */}
      </div>
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search