Home > OS >  How to pass CSS class names in reactJs
How to pass CSS class names in reactJs

Time:11-10

I want to change the width of a component whenever I click a button from another component

this is the button in BiCarret

import { useState } from "react";
import { BiCaretLeft } from "react-icons/bi";

const SideBar = () => {
  const [open, setOpen] = useState(true);

  return (
    <div className="relative">
      <BiCaretLeft 
        className={`${
          open ? "w-72" : "w-20"
        } bg-red-400 absolute cursor-pointer -right-3 top-5 border rounded-full`}
        color="#fff"
        size={25}
        onClick={setOpen(!true)}
      />
    </div>
  );
};

export default SideBar;

and this is the component I want to change the width on click

import "./App.css";
import SideBar from "./components/SideBar/SideBar";

function App() {
  return (
    <div className="app flex">
      <aside className="h-screen bg-slate-700"> #change the width here#
        <SideBar />
      </aside>
      <main className="flex-1 h-screen"></main>
    </div>
  );
}
export default App;

CodePudding user response:

You have two simple solutions, either:

  1. Create context Crete context and store Open value in it, change it on click and in App react to it.
  2. Dom manipulation In app add ID to element you would like to change and onClick in the other component use document.getElementById(THE_ID).classList.add("new-class-for-increased-width") which gets the DOM element and adds class to it.

CodePudding user response:

I just noticed that you want to change the width of the App's aside tag. Here is how to do it.

import { useState } from "react";
import { BiCaretLeft } from "react-icons/bi";

const SideBar = ({open, setOpen}) => {
  return (
    <div className="relative">
      <BiCaretLeft 
        className={`${
          open ? "w-72" : "w-20"
        } bg-red-400 absolute cursor-pointer -right-3 top-5 border rounded-full`}
        color="#fff"
        size={25}
        onClick={setOpen(!open)}
      />
    </div>
  );
};

export default SideBar;

And in the App component, the following:

import "./App.css";
import SideBar from "./components/SideBar/SideBar";

function App() {
  const [open, setOpen] = useState(true);

  return (
    <div className="app flex">
      <aside className={`${open ? 'w-72' : 'w-20'} h-screen bg-slate-700`}> #change the width here#
        <SideBar open={open} setOpen={setOpen} />
      </aside>
      <main className="flex-1 h-screen"></main>
    </div>
  );
}
export default App;

I assumed above that you want to change the value on both the child/Sidebar component as well as the aside tag in the App component.

  • Related