Search code examples
reactjsif-statementreact-functional-componentreact-state

How to set states inside ifcondition in functional component


How to set setEditOnClick(true) on condition inside functional component

const peopleCard = () => {
 const [isEditOnclick, setEditOnClick] = useState(false);
 const [peopleID, setpeopleID] = useState('');
return (
.....
.....some other code
.....

 {isEditOnclick ? 

    <CrudModal id={peopleID} />
    {setEditOnClick(false)}
     
    : null }

}

......
......
 <button onMouseEnter={() => setEditOnClick(true)}}

Am new to react kindly help me to fix this


Solution

  • You should not set the state 'setEditOnClick(true)' inside your JSX code because you are basically unrendering the CrudModal component. Instead, you should do the following:

        const PeopleCard = () => {
          const [isEditOnclick, setEditOnClick] = useState(false);
          const [peopleID, setpeopleID] = useState('');
        
          // Define a function to handle the mouse enter event on the button
          // Check if isEditOnclick is currently false
          // Set isEditOnclick to true using the setEditOnClick function
          const handleMouseEnter = () => {
            if (!isEditOnclick) {
              setEditOnClick(true);
            }
          };
        
          // Render the component's JSX code
          return (
            <>
              {/* some other code */}
              {isEditOnclick && <CrudModal id={peopleID} />}
              {/* some other code */}
              <button onMouseEnter={handleMouseEnter}>Edit</button>
            </>
          );
        };