JustLogin
JustLogin

Reputation: 1886

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?

Upvotes: 1

Views: 104

Answers (2)

Lakston
Lakston

Reputation: 31

You are applying classname to your Menu component so it is treated as a prop and not a class attribute.

You can either apply the classname inside your Menu component or pass the class as a prop like you did and use it, again, inside your menu component.

Upvotes: 0

Oleksandr T.
Oleksandr T.

Reputation: 77522

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>

Upvotes: 2

Related Questions