react newbie here once again. I'm trying to update the page with a note when pressing 'send' button. Honestly I tried for so long that I think my code is pretty much a mess rn.
Main func:
function MainLogged() {
const [sendingScreen, setSendingScreen] = useState(true);
let notes = [];
const [note, setNote] = useState('')
function onNoteChange(event){
const {value} = event.target;
setNote(value);
}
function afterButtonClick(event) {
notes.push(note);
setSendingScreen((prev) => !prev)
}
return (
<div id='main'>
{sendingScreen ? <MainBody noteCallback={onNoteChange} callback={afterButtonClick}/> : <ResetScreen callback={afterButtonClick}/> }
{console.log(notes)}
{
notes.map((singleNote) => {
return (<p id='single-note' className='note'>{singleNote}</p>)
})
}
</div>
)
}
then goes to component:
function MainBody(props) {
const {noteCallback, callback} = props;
return (
<div>
<p id='main-body'>{lorem}</p>
<div className='card text-center' style={{width: '18rem', alignSelf: 'center'}}>
<Input onChange={noteCallback} type='text' placeholder='My note is...' className='card-body information' />
</div>
<SendCardButton callback = {callback}/>
</div>
)
}
and finally (if necessary):
function SendCardButton(props){
const {callback} = props;
return (
<button type="button" className="btn btn-success toBeCentered" onClick={callback}>Send</button>
)
}
Using this code leaves notes array empty always.
Please if you can explain so I can learn and improve, I REALLY need it right now. Thanks a lot!
React does not rerender your component after you click the button because notes are not stored in state. You need declare notes this way:
const [notes, setNotes] = useState([]);
And then set them on button click, not just push the new one:
setNotes((prevNotes) => ([...prevNotes, note]));
That should be enough:) Feel free to comment if you have further questions