I’m trying to load an image asynchronously and only when it’s been loaded, display it in a React app.
JavaScript
x
20
20
1
componentDidMount() {
2
const img = new Image();
3
img.onload = () => {
4
this.setState({
5
originalImage: img,
6
});
7
}
8
img.src = './images/testImage.jpg'
9
}
10
11
render() {
12
return (
13
<main>
14
{
15
this.state.originalImage
16
}
17
</main>
18
);
19
}
20
I’m getting below error:
Objects are not valid as a React child (found: [object HTMLImageElement])
I would like to know why this error is happening. Of course if I just add an <img>
tag, it works fine.
Advertisement
Answer
React cannot directly display HTML Element. If you want to create elements programmatically you have to use functions provided by React.
JavaScript
1
40
40
1
componentDidMount() {
2
const url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRYd74A26KhImI1w9ZBB-KvWUcasVnQRe_UOrdZPqI4GOIN0mC3EA';
3
4
let img = React.createElement(
5
"img",
6
{
7
src: url,
8
},
9
)
10
this.setState({
11
originalImage: img,
12
})
13
14
15
let divExample = React.createElement(
16
'div',
17
null,
18
`Hello World`
19
);
20
this.setState({
21
divExample: divExample
22
})
23
}
24
25
render() {
26
return (
27
<div>
28
<div>Hi</div>
29
{
30
this.state.divExample
31
}
32
<main>
33
{
34
this.state.originalImage
35
}
36
</main>
37
</div>
38
);
39
}
40
React parses jsx element like div, img, HelloWorld (custom) etc. and create React Elements out of it.