1

As far as I understood its possible to add only one class to the element by doing className={styles.className} even if it's composed of many.

So at the current moment the code uses ternary operator in order to render different element styles depending on the state.cross value.

export default class Header extends Component {
  constructor(props) {
    super(props);

    this.state = { cross: false };

    this.showCross = this.showCross.bind(this);
    this.showLine = this.showLine.bind(this);
  }

  showCross() {
    this.setState({cross: true});
  }

  showLine() {
    this.setState({cross: false});
  }

  render() {
    return (
      <div onMouseEnter={this.showCross} onMouseLeave={this.showLine} className={styles.blockClose}>
        <a className={this.state.close ? styles.closeCross : styles.closeLine}>&nbsp;</a>
      </div>
    )
  }
}

What it actually does it makes 2 lines to look like a cross after state has been changed and transform has been applied.

:local(.closeLine) {
  ...20px line

  &::before {
    ...equal line
  }
}

:local(.closeCross) {
  composes: closeLine;
  transform: rotate(-45deg);

  &::before {
    transform: rotate(90deg);
  }
}


My question is:

Is it possible instead of conditional rendering just toggle class by doing smth like element.classList.toggle(className) to manage the styling of the element.

:local(.closeCross) {
  transform: rotate(-45deg);

  &::before {
    transform: rotate(90deg);
  }
}
2
  • 1
    You could do element.classList.toggle(className) directly in your click handler or in componentDidMount, however you'd be losing the benefits of Reacts declarative programming model, therefore taking control from React. Commented Mar 1, 2017 at 21:00
  • @riscarrott, so from you point of view it will be better to leave the way it is? Commented Mar 1, 2017 at 21:42

1 Answer 1

1

You can use the really awesome classnames package, which allows you to easily have multiple classes. I'm not sure of your final goal, but it would be easy to do something like:

<a className={classNames(
    styles.closeCross, { // <-- always applied
        [styles.closeLine]: this.state.close   <-- applied only when closed
    })}
>&nbsp;</a>

https://github.com/JedWatson/classnames

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.