K
K
Konstantin Basharkevich2016-10-27 08:11:18
BEM
Konstantin Basharkevich, 2016-10-27 08:11:18

Is it possible to use a mix of BEM classes in react components?

According to BEM, to modify the styles of a block, when it is inside another block, a mix of block and element styles is used. Is this approach possible if the nested block is represented by a react component? For example:

class Avatar extends React.Component {
  render() {
    return (
      <img className="avatar" src={this.props.user.avatarUrl} alt={this.props.user.name} />
    );
  }
}

class UserInfo extends React.Component {
  render() {
    return (
      <div className="user-info">
        <Avatar user={this.props.user} /> 
        <div className="user-info__name">{this.props.user.name}</div>
      </div>
    );
  }
}

Is it possible for an Avatar bean inside a UserInfo bean to have a mix of avatar and user-info__avatar classes ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Gushchin, 2016-10-27
@qodunpob

If I understand you correctly:

class Avatar extends React.Component {
  render() {
    const finalClassName = 'avatar ' + (this.props.className || '')
    return (
      <img className={finalClassName} src={this.props.user.avatarUrl} alt={this.props.user.name} />
    );
  }
}


class UserInfo extends React.Component {
  render() {
    return (
      <div className="user-info">
        <Avatar className="user-info__avatar" user={this.props.user} /> 
        <div className="user-info__name">{this.props.user.name}</div>
      </div>
    );
  }
}

Those. just pass className as props to the Avatar component, then merge into one className:
// выражение в скобочках нужно, чтобы не получилось 'avatar undefined', когда className не передан.
// Я рекомендую указать className, равное '', в defaultProps компонента Avatar
const finalClassName = 'avatar ' + (this.props.className || '')

Also, npm has a handy package https://www.npmjs.com/package/classnames , which allows you to form a string with classes. Your example would look like this:
const finalClassName = classnames({
  'avatar': true,
  [this.props.className]: !!this.props.className,
  'some-other-class': someCondition
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question