Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

onClick not working when I attempt to change value of variable

In React, I’m attempting to change the display of 2 elements when certain buttons are clicked on. I either want the title displayed, or an input to edit the title. My title div has a className of a variable named ‘titleDisplay’ with the value of ‘isDisplayed’. I have a function set up to switch it to ‘notDisplayed’

let titleDisplay = 'isDisplayed';
let editDisplay = 'notDisplayed';
const editDisplayed = () => {
        editDisplay = 'isDisplayed'
        titleDisplay = 'notDisplayed'
    }
<button onClick={editDisplayed} id="edit-btn">EDIT</button>
<div className={titleDisplay}>
   <h2 className='indieNotebookTitle'>{notebook?.title}</h2>
</div>
.isDisplayed {
    display: block;
}

.notDisplayed {
    display: none;
}

Not sure what I’m doing wrong since onClick has been working with functions up until now.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

React will only re-render a component in response to a state change. Reassigning a variable, by itself, almost never has any side-effects, unless the variable is used later. Your reassignment of editDisplay would only be visible to other functions within the same component binding (a very unusual occurrence to see in React, and usually an indicator of a logic problem).

You need to make the variables you try to change stateful instead. Also, consider using a boolean value rather than a string value. You may be able to use only a single state value instead, to toggle between the title and the edit.

const [editingTitle, setEditingTitle] = useState(false);
<button onClick={() => setEditingTitle(false)} id="edit-btn">EDIT</button>
<div className={editingTitle ? 'isDisplayed' : 'notDisplayed'}>
   <h2 className='indieNotebookTitle'>{notebook?.title}</h2>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading