Answer the question
In order to leave comments, you need to log in
How to correctly pass a class to a component?
Now I'm doing this:
Page.js
<Nav
items={this.state.menuItems}
className='page__nav'
/>
render() {
let { items, className } = this.props;
return(
<nav className={className + ' nav'}>
Answer the question
In order to leave comments, you need to log in
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>
);
}
}
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 questionAsk a Question
731 491 924 answers to any question