Home > OS >  React: how return a string from arrow function and use it inside a ClassName
React: how return a string from arrow function and use it inside a ClassName

Time:11-30

I have a Component:

import { useState } from "react";

export const Sidebar = () => {

    const [isOpened, setIsOpened] = useState(false);

    const handleClick = () => {
        setIsOpened(!isOpened);
    }

    const openedClassName = () => {
        let classNameString = "collapse";
        if (isOpened) {
            classNameString = classNameString   " show";
        }
        return classNameString;
    }

    return (

        <ul className="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
            
            <li className="nav-item active">
                <a className="nav-link" href="#" onClick={handleClick}>
                    <i className="fas fa-fw fa-folder"></i>
                    <span>Pages</span>
                </a>
                <div id="collapse1" className={`${openedClassName}`}>
                    <div className="bg-white py-2 collapse-inner rounded">
                        <a className="collapse-item" href="login.html">Login</a>
                    </div>
                </div>
            </li>
            <div className="text-center d-none d-md-inline">
                <button className="rounded-circle border-0" id="sidebarToggle"></button>
            </div>

        </ul>
    );
}

export default Sidebar;

I want to produce the className on the collapse1 BEFORE the rendering, so I added the openedClassName function.

But I have inside my class the entire arrow function, not the string...

this is test result:

Expected the element to have class:
      show
    Received:
      () => { let classNameString = "collapse"; if (isOpened) { classNameString = classNameString   " show"; } return classNameString; }

CodePudding user response:

You forgot to call your function. You're passing the function definition to the classname.

Just do

<div id="collapse1" className={`${openedClassName()}`}>

And it should work. Remember to use () to say that you want to run the function.

CodePudding user response:

solution: (forgot to call the function)

<div id="collapse1" className={`${openedClassName()}`}>

better solution

<div id="collapse1" className={`collapse ${isOpened ? 'show' : null}`}>

CodePudding user response:

I don't know if you consider it like dirty code, but I'd prefer to use:

<div id="collapse1" className={${isOpened && "collapse"}}></div>

If the state isOpened is true, it will add the collapse class, if it's not, it won't do anything

CodePudding user response:

After you created the function openedClassName, add following:

const myClassName = openedClassName();

Then in your jsx use it instead:

<div id="collapse1" className={`${myClassName}`}>
  • Related