JustLogin JustLogin - 1 month ago 9
CSS Question

Cannot toggle class for button in React.js

I want to make movement animation for

button
using class toggling just like in this example. For some reasons my code is broken: it calls the click handler, but does not affect classes.

There's the code (I use React, Classnames and Webpack):

index.jsx:

import React from "react";
import styles from "./index.css";
import classnames from "classnames";

export default class PlaylistButton extends React.Component {
onClick() {
alert("clicked");
$('.transform').toggleClass('transform-active');
}

render() {
return (
<button className = {classnames(styles.button, styles.transform)} onClick = {() => this.onClick()}>label</button>
);
}
}


index.css:

.button {
font-size: 30px;
color: white;
background-color: #5266ed;
margin-bottom: 5px;
border: none;
width: 300px;
height: 75px;
}

.transform {
-webkit-transition: all 2s ease;
-moz-transition: all 2s ease;
-o-transition: all 2s ease;
-ms-transition: all 2s ease;
transition: all 2s ease;
}

.transform-active {
margin-left: -200px;
}


What's the mistake?

Answer

The css-modules will replace your classname with a random string in run time. So, the your expected class name for styles.transform will not be transform because it will be replaced with a random string. To answer your question, you need to use styles.transformand styles.transform-active in your jquery.

onClick() {
    alert("clicked");
    $('.'+ styles.transform ).toggleClass(styles.transform-active);
  }

css-modules will convert your classnames as the following.

enter image description here

Hope this helps!

Comments