Using custom images in components react - reactjs

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?)

Related

I am confuse reactjs component design

How do I or what is the alternative method to break this layout into react component? The code below is bootstrap 4 for simplicity and what I want to achieve is something like this https://codedthemes.com/demos/admin-templates/material-able/bootstrap/default/ where contents are dynamic which is actually consist of different components. So what I am showing here is the simplified HTML code of the actual thing but has a similar structure. The question here how do I break them into components with this HTML structure? Many thanks in advance and appreciate any helps. Thanks again.
<div class="wholepage">
<navbar>
</navbar>
<sidebar>
<dynamiccontent>
</dynamiccontent>
<sidebar>
</div>
What you are describing is one of the selling points of React - the ability to modularise bits of code into what React calls components.
To build something like what you have linked you would need to nest components.
Using the example you might have an app.js that looks something like this.
import React from 'react'
import graph1 from './components/graph1'
import graph2 from './components/graph2'
const app = () => {
return (
<div>
<graph1 key1="props data goes here"/>
<graph2 key1="props data goes here"/>
</div>
)
}
export default app;
graph1 and graph2 are seperate components that have been imported and then nested in the app component as shown below.
The key1 attributes in each component accept values/functions that are passed down to graph1 and graph2 components for further processing and/or display. This is what allows you to make the content dynamic.
What I've mentioned above is very rudimentary but I think answers your question. ReactJS is a massive topic and will take a lot of practice to get used to. is well documented and there is a lot of fantastic documentation, examples and discussion online such as:
React components
React Props
React Design Patterns
DISCLAIMER: Fairly new to react myself, just trying to share the knowledge :)

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>
)

What the best way to import assets in React JS?

I'm currently working on a project with React JS, that contains lots of assets. And actually, I'm wondering what is the best way to import assets between these two methods :
- Creating a JSON file that contains all informations, with their assets paths (eg. mySuperImg: "../assets/img/myImage.jpg" then using the path for my image tags)
- Importing all assets directly in the component (or using the Context API, perhaps?) (eg. import {myImage} from "../assets/myImage.jpg" then using the img tag with that path <img src={myImage} alt="My Image"/>)
My questions : What the best way to import assets ? Is there a speed difference between these two methods ?
Thanks! Take care!
I'd say it depends on you. Whichever way you feel comfortable, you should go for it. Generally, I import the assets in the corresponding file, but the other way can also be used. Instead of json, you could use js approach as well, similar to how we export actions, for eg,
export const ADD_PROJECT = "add_project";
export const FETCH_PROJECTS = "fetch_projects";
You could use something like,
export const IMAGE = require("the location to your image");
To answer if it would take more time, I don't think that there would be any performance issue, as we use a similar approach for the actions most of the times.
it's best to keep the images in assets and use them in your source, if you work with the JSON file then you have to keep track of both of them and it will mess up as you say you have a lot of assets.

Require image from state returns error

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>

How to import a component or file in React using variables?

I'm building a web app using React that shows the blueprint for the building you select, in an already selected campus.
I have a "Content" component that loads the campus or building map, depending what you chose.
The "BuildingMap" component needs to load a specific blueprint according to what building you selected. It gets the props.building with the name of the building but I don't know how to load a component using that variable.
I have tried import, fetch and require but nothing seems to work.
Please help.
My code looks something like this:
//Content Component
<BuildingMap building={selectedBuilding} campus={selectedCampus} />
//BuildingMap Component
import *MyBlueprint* from (specific folder depending on the campus selected)
class BuildingMap extends React.Component {
render(){
return (
<div className="blueprint" id={this.props.building}>
{*MyBlueprint*}
</div>
)
}
}
Unfortunately, you cannot import/require components dynamically in React environment.
Depending on how many buildings/blueprints there are, it's possible to import them one by one, create component-building map and pick component by building ID.
If there are many/infinite components to load, I would surely pick another method - don't know content of your problem.
import BlueprintA from './BlueprintA'
import BlueprintB from './BlueprintB'
import BlueprintC from './BlueprintC'
// ...
class BuildingMap extends React.Component {
render(){
const C = {
buildingA: BlueprintA,
buildingB: BlueprintB,
buildingC: BlueprintC,
// ...
}[this.props.building]
return (
<div className="blueprint" id={this.props.building}>
<C />
</div>
)
}
}
This question is pretty old but as I was looking for how to solve the same problem let me give my answer. It can be done with dynamic import React.lazy:
const OtherComponent = React.lazy(() => import('./OtherComponent'));
See more details here: https://reactjs.org/docs/code-splitting.html#reactlazy
To add to #Andreyco's answer:
Using a lookup table of string IDs/names to component classes is a typical React idiom. One common use case is a modal manager component that can render multiple different types of modals. For some examples, see Dan Abramov's answer at "How can I render a modal dialog in Redux?" (not Redux-specific), as well as some of the related articles in the React Component Patterns#Modal Dialogs and Redux Techniques#UI sections of my React/Redux links list.
Per #azium's comment: it is definitely possible to use dynamic importing (via require.ensure() or the new import() function) to load chunks at runtime, and you could add the exports from those dynamically imported chunks into a lookup table when they are loaded.

Resources