I have a JSON that is providing a source prop to a component that would use it to create an <img src={source} ... />
element. I have seen on stackoverflow here and here that I need to import the picture with template literals to use it, <img src={require(`${source}`)} alt={title}/>
where source is a prop, title is a prop.
The code is pasted below for reference. Thank you for your patience and assistance!
app.js
parseJson(){
var data = require('./highlights.json');
for (var i = 0; i < data.length; i++) {
var obj = data[i];
console.log("source: " + obj.src);
}
return data.map((obj, key) =>
<Highlight source={obj.source} link={obj.href} title={obj.title} desc={obj.desc} key={obj.src}/> // returns the components and passes in the appropriate props
)
}
render() {
return (
<div className="App">
<Menubar/>
<div>
<Profilepic onClick={this.toggleModal}/>
</div>
<div className = "HighlightsContainer">
{this.parseJson()} // returns a bunch of components here
</div>
<UploadButton/>
<UploadWindow show={this.state.uploadWindowOpen}/>
<Modal show={this.state.isOpen}
onClose={this.toggleModal}>
<Signup/>
</Modal>
<PhotoViewer show={this.state.photoViewerOn}/>
</div>
);
}
highlight.jsx
import React from 'react';
let Highlight = function statelessFunctionComponentClass(props) {
// the 4 props that are passed in
let source = props.source;
let link = props.link;
let title = props.title;
let desc = props.desc;
let style = {
position: 'relative',
width: '300px',
height: '300px',
background: 'blue',
display: 'inline-block'
};
//returns the component of an image button
return (
<button style = {style}>
<a href={link}>
//the require statement is giving issue, without it buttons are created
//without require, with it i get the error described below.
<img src={require(`${source}`)} alt={title}/>
</a>
<div id="highlight1-title">{title}</div>
<div id="highlight1-desc">{desc}</div>
</button>
);
};
export default Highlight;
the error - this error was fixed by changing to obj.src Error: Cannot find module 'undefined'.
16 | return (
17 | <button style = {style}>
18 | <a href={link}>
> 19 | <img src={require(`${source}`)} alt={title}/>
20 | </a>
21 | <div id="highlight1-title">{title}</div>
22 | <div id="highlight1-desc">{desc}</div>
** new module error **
Error: Cannot find module 'highlights/1.jpg'.
statelessFunctionComponentClass
C:/Users/auser/Documents/.../src/Component/Highlight.jsx:19
16 | return (
17 | <button style = {style}>
18 | <a href={link}>
> 19 | <img src={require(`${source}`)} alt={title}/>
20 | </a>
21 | <div id="highlight1-title">{title}</div>
22 | <div id="highlight1-desc">{desc}</div>