Home > Back-end >  How to handle the onClick function after its been clicked
How to handle the onClick function after its been clicked

Time:06-02

Ive created a expandList variable to show a list on click. After the click happens it shows the list but i am unable to close it.

const ExpandList = ({ students }) => {

    const { grades }  = students;
    const [isExpanded, setIsExpanded] = useState(false);

    

    function HandleClick(index) {
        if (isExpanded === index) {
            return setIsExpanded(null);
        }
        setIsExpanded(index);
    }

    return (
        <div className="grades">
            <button onClick={HandleClick}>
                { isExpanded ? <ImMinus/> : <ImPlus/> }
            </button>
            {isExpanded ? (
                <div className="grades">
                    {grades.map((grade, index) => 
                        <ul key={index}>Test {index   1}: {grade}%</ul>)}
                </div>
            ) : null}
            
        </div>
    )
};

Not sure how to handle the HandleClick function after its been clicked.

CodePudding user response:

The best way to toggle isExpanded is to take the inverse value of isExpanded

You can achieve this like this :

 function HandleClick(){
   setIsExpanded(!isExpanded);
 }  

Now every time you click on the button, the method will change the state of isExpanded to its inverse value

If the value is false it will change to true and so on


Here is a documentation about the NOT operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT

  • Related