Require image from state returns error - reactjs

to learn React I created a REST API to grab data from and after some issues I got it working with fetching data in my state, and rendering the component with data depending on state.
now, i'm trying to use this.state.data.Image, which is a simple string like example.jpg, to show different images which I have stored locally in my project. the pictures are stored in the src directory while I have my components in a component directory, so to grab the picture I have to use ../example.jpg. if i do this grab with an import, like this:
import example from '../example.jpg';
<img src={example} alt=""></img>
it all works well, but this doesn't work if i want to show the image depending on which set of data i'm grabbing from the API. so I'm trying something like this:
<img src={require("../" + this.state.data.Image)} alt=""></img>
./src/App.test.js
Module not found: Can't resolve './App' in 'C:\Users\MyName\Code\react-test\src'
For boilerplate I use create-react-app, which is why this App.test.js file is generated. Why is this issue arising? Am I missing a key point? Any pointers appreciated!

You cannot write src={require("../" + this.state.data.Image)} in jsx files.You have to import all image files as
import example1 from '../example1.jpg';
import example2 from '../example1.jpg';
<img src={example1} alt=""></img>
based on this.state.data.Image you can import images
You can create a map as
imageMap = ["img1":{example1},
"img2":{example2}
]
and write
const inputImg = this.state.data.Image
<img src={imgMap[inputImg]} alt=""></img>

Related

Using custom images in components react

I have a react component that is used many times on a products page. Each of the components has its own image. Is there a way to dynamically import an image? For example something like
function productPage({imgPath}){
import img from imgPath
return <img src={img}/>
}
and when I use the component I can do something like
<productPage imgPath="/pathToImage">
I have only come across answers that use require (<img src={require("/pathToImage")} />) However, this method does not work for me. Images only load when I use import. I am not sure why this is (maybe using create-react-app only allows for import?)

React unable to display images from local path

I'm new to react, I'm trying to display images from the src/images folder.
but after inserting the correct path, then also the image is not visible.
Here you can see my img tag path and on the left side folder structure
From the Image you provided, looks like you used require("path...") which is not a good way to do so, its valid tho, but not a good practice, its recommended and is common to use import X from "somewhere" syntax.
I suggest you to use either of these two ways to use images in react.
put images in public folder and use relative links in the href tag, i.e:
<img href="/images/panda.png" alt="cute panda" />
put images inside a folder somewhere inside src folder like you did in the image and import images using ES import syntax, and use imported image variable in {} expression for src prop, i.e:
import PandaImg from "../images/panda.png"
const Panda = ()=>{
return <img src={PandaImg} alt="cute panda" />
}
Here is a CodeSandbox Example may help you further explore the code in broader context.

Can't Render Image When Path Stored in React Variable

I have a lot of images I need to use in my react app, so I don't want to import them one by one. To that end, I'm using reqiure(). However, while require works when used like this below:
return <img src={require("./images/lets_go.png")} />
if I store that path in a variable:
let v = "./images/lets_go.png";
return <img src={require(v)} />
I get Error: Cannot find module './images/lets_go.png'
Why won't it allow me to use the path stored in a variable (it's the exact same path) and how can I make it work?
this will work using a 'Partial' require, where you give the path as text and and the image name can be the varible. the reason this is happening is related to how webpack is meant to handle static paths.
What we know works, (static image path):
<img src={require("./images/lets_go.png")} />
Trying to make the path a varible like this we found does not work
let v = "./images/lets_go.png";
<img src={require(v)} />
What will work when trying to make the path a varible
let v = "lets_go.png";
<img src={require(`./images/${v}`).default} />
Note that .default needs to be added at the end of the require as of may/2021 due to a error related to react scripts. this might be fixed and not needed if you're reading this in the future.
you'll need to store all your images in the same folder of course, but this lets you dynamically load high volumes ofimages in react/js without needing to manually import them all into the code.
Either you may import the image and bind it to src attribute like its done in create-react-app with the logo as follows:
import logo from './logo.png' // relative path to image
class Home extends Component {
render() {
return (
<img src={logo} alt={"logo"}/>
)
}
}
Or, if you used create-react-app cli to create your project then your public folder is accessible. Just create the images or assets folder in public and you may access it in jsx as follows:
public/images/ -> store images here
<img src="/images/home.png" /> -> use it like this in jsx

React.JS React-Router-Dom applying css on every routes

i'm a beginner in react.js and i recently discovered react-router-dom but i have an issue with it if i apply css to my file all the other routes have this css how could i fix that issue?
My Code:
https://i.imgur.com/9imDEdU.png
https://i.imgur.com/GMLk6Q1.png
I guess it's because it import this page on every page but i have no idea how to fix the problem
You can import the css file inside your react component.
For example, you can import the login.css file in your Login component
Edit:
If you want to load the css files on demand, refer
http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
The problem occurs because of react bundle all things together.
You may need to set different className for your every page root parent div.
Also, Another way is to set a different CSS/SCS file in the corresponding view Component.
Like if I consider Login.jsx cmponent it return method would be like that:-
For Login.jsx:-
return(
<div className="login-container">
</div>
)
For Registration.jsx:-
return(
<div className="registration-container">
</div>
)

Dynamically Importing Images Based on a Variable

I have a requirement to select, from a local source, an image based on the value passed back from the REST API I am using. For example:
//Psuedo-call from the API
var imageIdToSelect = response.data.imageId
//Then later in the render()
<img src={ baseUrl + imageIdToSelect } />
I have a solution to this, which is to use require() as that allows me to append the url as such:
<img src={ require(baseUrl + imageIdToSelect) } />
This works fine, however, I am using a Microsoft TSLINT setup that does not allow require() over the prefered import at the top of the file "no-require-imports".
I know I am not meant to let linting tools control my work to the point where I am just blindly following rules. So my question is two-fold:
Why is it frowned upon to use require() in such a way. One reason I could think of is that if all of the external files/resources are declared at the top of the file, then you don't have to look through the source to find them hidden in functions.
What would the import x from './' solution look like here? I have seen people creating index.js and index.d.ts files inside their image folders to import and export all the images inside but that seems a tad extraneous.
Edit: I also have just realised that using require() with a non-literal string is a violation of my ts-linting too.
Thanks in advance

Resources