Home > Mobile >  onClick not working when I attempt to change value of variable
onClick not working when I attempt to change value of variable

Time:04-09

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.

CodePudding user response:

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>
  • Related