Reputation: 97
I've started creating a web app like Facebook messenger in React.js. I'm getting some input from user and then using state and it is working perfectly. I'm showing that input in console that is also working perfectly as it ca be seen in screenshot of console
the problem is i'm trying to show the input(which user enters) and it's not working Here's my code
import React, {useState} from 'react';
import './App.css';
function App() {
const [input, setInput] = useState('');
const [messages,setMessages]=useState([]);
console.log(messages);
const sendMessage = (event)=>{
setMessages([...messages,input]);
setInput('');
}
return <div className="App">
<h1>Messenger</h1>
<input value={input} onChange={event => setInput(event.target.value)}/>
<button onClick={sendMessage}>Send Message</button>
{
messages.forEach(message =>{
<p>{message}</p>
})
}
</div>;
}
export default App;
Upvotes: 1
Views: 50
Reputation: 6766
Use map
instead of forEach
. map
method will return a new array with the result of the callback function for each element in the array.
{ messages.map(message => <p>{message}</p>)}
Working demo: - https://codesandbox.io/s/compassionate-chatterjee-2eml6?file=/src/App.js
Upvotes: 1
Reputation: 10675
Snapshot:
import React, {useState} from 'react';
function App() {
const [input, setInput] = useState('');
const [messages,setMessages]=useState([]);
console.log(messages);
const sendMessage = (event)=>{
setMessages([...messages,input]);
setInput('');
}
return <div className="App">
<h1>Messenger</h1>
<input value={input} onChange={event => setInput(event.target.value)}/>
<button onClick={sendMessage}>Send Message</button>
{
messages.map(message =>
<p>{message}</p>
)
}
</div>;
}
export default App;
Here is the working code sandbox link
Upvotes: 0
Reputation: 6829
You have to use map()
which iterates over a list, transforms each member of that list, and returns another list of the same size with the transformed members instead of forEach()
which iterates over a list and applies some operation with side effects to each list member.
Method 1:
{
messages.map((message) =>(
<p>{message}</p>
))
}
Method 2:
{
messages.map((message) =>{
return <p>{message}</p>
})
}
Upvotes: 1