Roy
Roy

Reputation: 1922

How to add className to component based on state without removing initial className

I have a component that is toggleable:

class HamburgerMenu extends React.Component {

    constructor(props){
        super(props)
        this.state = {
            toggle: false,
        }
    }

    Toggle() {
        this.setState((currentState) => ({
            toggle: !currentState.toggle
        }));
    }

    render() {
        return (
            <StyledHamburgerMenu className="HamburgerMenu" onClick={ () => this.Toggle() }>
                <FontAwesomeIcon icon="bars" />
            </StyledHamburgerMenu>
        )
    }
}

and I want to add a class name to a div (extended-right-bar) jsx element in a separate file:

function App() {
  return (
    <div className="App">
      <div className="grid-display">
        <div className="right-bar">
          <HamburgerMenu /> 
          <PlusButton /> 
        </div>
        <div className="extended-right-bar">
          <h1 className="main-title">Notes</h1>
          <div className="folders-section">
            <h2>Folders</h2>
            <Folder name="folder" />
            <Folder name="folder" />
            <Folder name="folder" />
            <Folder name="folder" />
          </div>
          <div className="tags-section">
            <h2>Tags</h2>
            <Label name="buisness" />
            <Label name="buisness" />
            <Label name="buisness" />
          </div>
        </div>
        <div className="main">
          <NoteWindow />
        </div>
      </div>
    </div>
  );
}

How can I do that? They're imported and exported to each other

Upvotes: 0

Views: 72

Answers (2)

Tanmay Verma
Tanmay Verma

Reputation: 263

You can use redux to pass classValue on toggle to the different component.

const Component = (props) => {
    const className = props.classValue ? "extended-right-bar " + props.classValue : "extended-right-bar";

    return (
      <div className={customProps.className}>
        <h1 className="main-title">Notes</h1>
        <div className="folders-section">
          <h2>Folders</h2>
          <Folder name="folder" />
          <Folder name="folder" />
          <Folder name="folder" />
          <Folder name="folder" />
        </div>
      </div>;
    );
}

Upvotes: 1

muhmann
muhmann

Reputation: 201

You can use

element.classList.add("className");

to add a class without overwriting the existing ones.

Replace element and className accordingly

Upvotes: 1

Related Questions