V
V
Vladimir Golub2019-04-25 12:01:56
React
Vladimir Golub, 2019-04-25 12:01:56

How to correctly pass a class to a component?

Now I'm doing this:
Page.js

<Nav
  items={this.state.menuItems}
  className='page__nav'
/>

Nav.js
render() {
        let { items, className } = this.props;

       return(
            <nav className={className + '  nav'}>

Maybe there are better ways?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Fat Lorrie, 2019-04-25
@Free_ze

Ideally, the component approach does not need to pass classes from outside. The component itself knows how it needs to be displayed. To position it, we wrap it and act on the wrapper.

export function css(...classNames) {
    let result = [];
    for(let i=0; i<classNames.length; ++i) {
        if (Array.isArray(classNames[i])) {
            result = result.concat(classNames[i]);
        } else {
            result.push(classNames[i]);
        }
    }
    return result.join(' ');
}

import * as React from 'react';
import {css} from '../utils.js';

import './MyComponent.scss';
const BLOCK_CSS = 'my-component';
const BLOCK_MODIFIED_CSS = BLOCK_CSS + '--modifier';
const ELEMENT_CSS = BLOCK_CSS + '__element';


export class MyComponent: React.Component {
    ...
    public render() {
        const blockStateCss = [BLOCK_CSS];
        
        if (this.state.modificationNeeded) {
            blockStateCss.push(BLOCK_MODIFIED_CSS);
        }

        return (
            <div className={css(blockStateCss)}>
                <div className={css(ELEMENT_CSS)}>
                    ...
                </div>
            </div>
        );
    }
}

A
Anton Spirin, 2019-04-25
@rockon404

There is only one correct way.
Just read about ways to style React components and choose the one you like best and best suits your project.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question