i am new to reactjs, i have been trying to make my own reactjs projects so I came into this strange bug I have in my code. I modified a array of strings on submission of a button using input from a textarea tag. the array changes but I can't see the changes in the form of jsx list. i tried to map over it but it does not work.
import {useState,useRef} from 'react'
const quotes = ['hi there','greetings']
const listOfItems = quotes.map((item)=>
<li key={item}>{item}</li>
);
function App() {
const refrence =useRef()
function sub (event){
event.preventDefault();
quotes.push(refrence.current.value);
const listOfItems = quotes.map((item)=>
<li key={item}>{item}</li>
);
console.log(quotes)
return
}
return (
<>
<form onSubmit={sub}>
<label>type your text here</label>
<textarea ref={refrence} name='text' type='text' ></textarea>
<button type='submit'> press me</button>
</form>
{listOfItems}
</>
);
}
export default App;
CodePudding user response:
React will rerender only when you change state
or when you change props of component
. you don't do any of that.
to trigger rerender you must store list of components in state and change that
import {useState,useRef} from 'react'
function App() {
const [quotes, setQuotes] = useState(['hi there','greetings'])
const refrence =useRef()
function sub (event){
event.preventDefault();
setQuotes((old)=>[...old, reference.current.value])
console.log(quotes)
return
}
return (
<>
<form onSubmit={sub}>
<label>type your text here</label>
<textarea ref={refrence} name='text' type='text' ></textarea>
<button type='submit'> press me</button>
</form>
{quotes.map((item)=>
<li key={item}>{item}</li>
)}
</>
);
}
export default App;