mayuri mayuri - 4 years ago 157
React JSX Question

Inline styling with React

I want to include below style in React js file to add asterisk after label.

.required:after {
color: #e32;
content: ' *'; }


I tried below code, but it is giving me astericks before label

const styles = {
required:
{
after:
{
content: "*",
color: "red"
}
}};

Answer Source

I think this is not possible. Some inline styles constructions are not present yet in React. I will try to check the documentation and to provide you the link.

Why don't you use className inside your JSX and refer the CSS file for that class name?


UPDATE:

In React, inline styles are specified as objects — which you did. You note the camelCased key style names and values are usually strings:

var divStyle = {
  color: 'white',
  backgroundImage: 'url(' + imgUrl + ')',
  WebkitTransition: 'all', // note the capital 'W' here
  msTransition: 'all' // 'ms' is the only lowercase vendor prefix
};

React.render(<div style={divStyle}>Hello World!</div>, mountNode);

Vendor prefixes other than ms should begin with a capital letter. This is why WebkitFilter has an uppercase "W".

For instance, this would work:

return (
        <div>
          <span>Something</span>
          <div style={{position: 'absolute', WebkitFilter: 'blur(10px) saturate(2)'}} />
        </div>
    );

However, as explained here using :after won't work.

Here is the example usig CSS:

class Example extends React.Component {

  render() {
    return ( <div className = "required">Test</div> );
  }
}

ReactDOM.render( < Example / > , document.getElementById('root'));
.required:after {
color: #e32;
content: ' *'; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download