'How to add an image to be returned by a map in REACT (JS)
I'm building a chatbox, on a card I have a messageList that I made with useState:

I'm trying to add images to the initMessageList to be displayed on the card with preview using useRef but it does not show the image (I'm changing the 'messageList' func):
function ConvBoard({ name }) {
const [initMessageList, setMessageList] = useState([])
const messageList = initMessageList.map((now, key) => {
if (now.Image) {
return <img src={preview} />
}
return <Message text={now.text} key={key} />
});
let newText = useRef(null);
const addMessage = () => {
if (newText.current.value != "") {
setMessageList([...initMessageList, {
text: newText.current.value,
key: initMessageList.length
}])
newText.current.value = ""
}
}
const onKeyFunc = function onKeyEnter(e) {
if (e.key === "Enter" && newText.current.value != "") {
{ addMessage() };
}
}
const [image, setImage] = useState();
const [preview, setPreview] = useState();
const pressRef = useRef();
useEffect(() => {
if (image) {
const reader = new FileReader()
reader.onloadend = () => {
setPreview(reader.result)
};
reader.readAsDataURL(image)
setMessageList([...initMessageList, {
text: preview,
key: initMessageList.length
}])
} else {
setPreview(null)
}
}, [image]);
return (
<Tab.Pane eventKey={name}>
<Card className='card'>
<extraWarper className="extra">
{messageList}
</extraWarper>
</Card>
<InputGroup>
<FormControl className='inputLine' ref={newText}
placeholder="your text" onKeyPress={onKeyFunc}
/>
<Button variant="outline-secondary">record</Button>
<DropdownButton title="upload" variant="outline-secondary">
<button onClick={(event) =>
pressRef.current.click()
}>
Send image
</button>
<input ref={pressRef} id="filePicker" style={{ display: "none" }} type={"file"}
onChange={(event) => {
const file = event.target.files[0]
if (file) {
setImage(file)
} else {
setImage(null)
}
}
} />
</DropdownButton>
<Button variant="outline-secondary" onClick={addMessage}>send</Button>
</InputGroup>
</Tab.Pane>
);
export default ConvBoard }
but when i try to add an Image its blank. Any ideas? (Sorry for the mess, and thank you!)
Solution 1:[1]
There is no now.Image in this code.
if (now.Image) {
return <img src={preview} />
}
return <Message text={now.text} key={key} />
});
there may be now.Text which represents now.Image and preview in your code
because you set it in this part of code
setMessageList([...initMessageList, {
text: preview,
key: initMessageList.length
}])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Michal Šajdík |


