volna
volna

Reputation: 2610

Webpack & Css-loader. How to create dynamic className for React?

The project has the following reference, which returns a string:

const left = slide.imageLeft; // introLeft


And further renders it inside React Component. But it returns as a string styles.imageLeft and since webpack doest convert it into corresponding bundled class like 914u923asdsajdlj1l23 the styles are not applied.

<div className={`styles.${left}`}>&nbsp;</div>


P.S I did try to eval, but it drops 2 errors.

There is an internal error in the React performance measurement code. Did not expect componentDidMount timer to start while render timer is still in progress for another instance.

And

ReferenceError: styles is not defined

Can you please suggest the possible ways to achieve dynamic class generation for css-loader.

Upvotes: 0

Views: 923

Answers (1)

xxfast
xxfast

Reputation: 737

You have to define the style within the render(), or within the component definition, like this

render: function(){
  var myStyle = {
    // your style rules go here
  };
  return(
    <div style={myStyle}>
      {this.props.children}
    </div>
  )
}

in a way, this is already dynamic, because all you have to do is to change to style and it'll make sure that the component will re-render on update

Upvotes: 1

Related Questions