mayuri
mayuri

Reputation: 135

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"
        }
        }};

Upvotes: 2

Views: 7586

Answers (2)

prosti
prosti

Reputation: 46291

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>

Upvotes: 0

Robsonsjre
Robsonsjre

Reputation: 1606

Inline styles cannot be used to target pseudo-classes or pseudo-elements. You need to use a stylesheet.

Try to change your logic before trying this approach.

You can check similar approach here in this issue: CSS pseudo elements in React

Upvotes: 2

Related Questions