KarimZ
KarimZ

Reputation: 37

How to toggle class of a div element by clicking on a button that is inside another functional component (another file)?

I want to toggle class of container (file 2) by an onClick on the button that is inside another component file.

The button has already an onClick function and I want to make it so it calls on two functions. Two toggle functions for the button and two class toggles for the container.

Hope it makes sense.

Here is my code so far:

Button component (File 1)

import React, {useState} from "react";
import "./Sort.scss";

const Sort = () => {

    const [toggleSortIcon, toggleSortIconSet] = useState(false);

    return (
        <div className="tools">
            <button 
            onClick={() => toggleSortIconSet(!toggleSortIcon)} 
            className={`sort ${toggleSortIcon ? "horizontal" : "vertical"}`}>
            </button>
        </div>
    );
}

export default Sort;

Div container component that I want to change the class of (File 2)

import React, {useState} from "react";
import "./WordContainer.scss";
import UseAnimations from "react-useanimations";


const WordContainer = ({title, definition, example}) => {

  const [toggleSize, toggleSizeState] = useState(false);

  return (
    <div className={`container ${toggleSize ? "big" : "small"}`}>
      <div className="content">
        <h2>{title}</h2>
        <p>{definition}</p>
        <h3>Example</h3>
        <p>{example}</p>
      </div>
      <img onClick={() => toggleSizeState(!toggleSize)} src="./resize.svg" alt="resize" className="resize"/>
      <div className="bookmark">
        <UseAnimations
          animationKey="bookmark"
          size={26}
        />
      </div>
    </div>
  );
}

export default WordContainer;

Upvotes: 0

Views: 111

Answers (1)

Nicolas SEPTIER
Nicolas SEPTIER

Reputation: 851

You could either have a global state management system (redux, or with custom hooks) that you can use to store the icon size.

Or you could simply provide a callback to your component that stores the icon size in a parent component that then feeds it back to your Something like this:

const [size, setSize] = useState(/* default value */);

render() {
  <>
    <Sort onSizeToggle={setSize} />
    <WordContainer size={size} />
  </>
}

Upvotes: 1

Related Questions