0

Is there any standard way to add dynamic stylesheet based CSS class into DOM using ReactJS (I am not talking about inline styles) ?

I know I could do this using standard JavaScript or jQuery, probably best in componentDidMount life cycle event, but I am curious if there's any standard way of doing this purely using React, that also reduces DOM mutation as much as possible.

Also please note that I am talking in the context of a simple web application that does not use nodejs.

1 Answer 1

2

The recommended way is to use classnames. it is a function that takes an object of keys that are either true or false, and returns a string of only true keys.

so you would do something like:

...
import cx from 'classnames';

const MyComponent = React.createClass({
   propTypes: {
      isVisible: React.PropTypes.bool
   },

   render() {
      let classes = cx({
                css-class: true,
                css-visible: !!this.props.isVisible   
             });

      return (
              <div className={classes}>
                 Hello World!
              </div>
      )
   }
});

this would create a div that gets the css classes css-class and css-visible, however css-visible would only be applied if this.props.isVisible existed or was true.

UPDATE: to include the css properties themselves.

...
render() {
   let styles = { "border": "1px solid black" };

   return (
      <div style={styles}>
        Hello World!
      </div>
   );
}
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry but I guess this cannot be used without using node. How can I use it in a simple web application like in Asp.Net MVC? I mentioned this in my question already.
Also I want these classes to be added in DOM along with their properties like for e.g css-class {border:'1px solid black'}. Will this can be done using your mentioned way?
You wouldn't need to use Node to use classnames you could just include it in your application whatever way you liked. In your post you say you don't want to do inline styles, but if your wanting to include the actual css properties (e.g. border: 1px) that would be done with inline css. See the updated answer for how you would include the css properties.

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.