Search code examples
javascriptreactjsstateless

Is it okay to add/remove classes in stateless react component


I have a stateless component which acts like an accordion. On click of the container div I toggle a couple of css classes on some of the child components. Is it okay it directly change the classes in the dom or should I be converting this stateless component to a stateful component and handle the class toggle through the state?

import React, {PropTypes} from "react"

const Accordian = ({children,label,align}) => {
    return(
            <div class={"accordian-tab " + (align === "left" ? "accordian-tab-left" : "")} onClick={
                (e) => {
                    e.target.parentNode.getElementsByClassName("panel")[0].classList.toggle("show");
                    e.target.parentNode.getElementsByClassName("accordion")[0].classList.toggle("active");
                }
            }>
                <button class="accordion">{label}<i class="material-icons arrow-icon">keyboard_arrow_down</i></button>
                <div class="panel">
                    {children}
                </div>
            </div>
    )
}

Accordian.propTypes = {
    label: PropTypes.string.isRequired
}

export default Accordian;

Solution

  • If you are not worried about the state being stored then you should be fine to leave it stateless. However there is a chance that the component will be redrawn if your props change, at which point you would lose its "state" and the component would seemingly reset.