JustLogin JustLogin - 29 days ago 7
CSS Question

React components do not use specified styles for some reasons

I'm creating a React component which uses some other components. But when I specify styles in the parent component for children, they do not use specified styles. But if I wrap children in div blocks, they do.

Here's my code:

index.css:

.playlistsMenu {
position: absolute;
left: 0;
}

.elementsMenu {
position: absolute;
right: 0;
}


index.js, parent component code. It not works!

render() {
return (
<div>
<Menu className={styles.playlistsMenu}/>
<Menu className={styles.elementsMenu}/>
</div>
);
}


But if I wrap my
Menu
components with
div
, everything is OK!

render() {
return (
<div>
<div className={styles.playlistsMenu}>
<Menu/>
</div>
<div className={styles.elementsMenu}>
<Menu/>
</div>
</div>
);
}


If I apply styles directly in child component (
Menu
), it also works fine!

What's the problem, and how do I solve it?

Answer

You pass className to Menu, it is a propetry, so you need in Menu component get className property and pass it to element, in this case I think you want to set className for root node

// Only for example
const styles = {
  playlistsMenu: 'playlistsMenu',
  elementsMenu: 'elementsMenu'
};
  

class Menu extends React.Component {
  render() {
    return <div className={ this.props.className }>Menu</div>
  }
}

class App extends React.Component {
  render() {
    return <div>
      <Menu className={styles.playlistsMenu} />
      <Menu className={styles.elementsMenu} />
    </div>
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
.playlistsMenu {
  color: red;
}

.elementsMenu {
  color: blue;
}
<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>