React -- Mapping specific images to specific cards - reactjs

Trying to map specific images to specific card components as backgrounds. Problem - When I pass data.bgUrl into style={{ backgroundImage:`url(${data.bgUrl})`}} the result is surrounded by quotes ("img1") instead of just path name (img1). As a result, images won't load. Any insights?
import AthleteData from "../athletes.json";
import img1 from "../assets/img1.png";
import img2 from "../assets/img2.png";
import img3 from "../assets/img3.png";
import img4 from "../assets/img4.png";
....etc
import Card from "./Card";
import "./cards.scss";
export default function Cards() {
return (
<div className="cards-container">
<div className="cards">
{AthleteData.map((data, key) => {
return (
<div
key={key}
style={{
backgroundImage: `url(${data.bgUrl})`,
}}
>
<Card
key={key}
name={data.name}
date={data.date}
link={data.link}
/>
</div>
);
})}
</div>
<h3>Load More Cards</h3>
</div>
);
}

If you used backgroundImage in style, you don't need to import images. Please check your data.bgUrl is the correct path for each image.
also, set the image size through width and height, or backgroundSize in the style. You may need to set backgroundRepeat in the style as well.

I'm assuming that the 'AthleteData' you are importing is an object where one of the properties is called 'bgUrl' and that the value of that property is set to be a string such as 'img1'. The problem with that, if it is the case, is that the line where you are attempting to call that property (of bgURL) is that it still only represents a string, even if you have an imported variable that is called 'img1' as well. In your Athletes.json file you would want to have a dynamic reference to the image location. The problem with this is that .json files don't support import statements.
What I would recommend doing is to make a simple Javascript file where you import all your images as you did above and set them into a single object below them. Set the property 'bgUrl' to the dynamic references that those import statements create, and then you should be good. I will demonstrate below:
//This would be the new athletes.js file. Not a .json file
import img1 from "../assets/img1.png";
import img2 from "../assets/img2.png";
import img3 from "../assets/img3.png";
import img4 from "../assets/img4.png";
....etc
const AthleteData =
[
{name: 'Athlete1', bgUrl:img1, ...},
{name: 'Athlete2', bgUrl:img2, ...},
{name: 'Athlete3', bgUrl:img3, ...}
]
export default AthleteData
Then when you import this and use it in your jsx it would look like so:
import AthleteData from "../athletes.js";
// No longer importing those image refrences here
import Card from "./Card";
import "./cards.scss";
export default function Cards() {
return (
<div className="cards-container">
<div className="cards">
{AthleteData.map((data, key) => {
return (
<div
key={key}
style={{
backgroundImage: `url(${data.bgUrl})`,
}}
>
<Card
key={key}
name={data.name}
date={data.date}
link={data.link}
/>
</div>
);
})}
</div>
<h3>Load More Cards</h3>
</div>
);
}
Everything should roughly be the same in your jsx but you wouldn't need the import statements.

Related

Why local svg icons not resolve in react.js projects?

I have local icons, and I add icons in build folder like screenshot below, then I was import icons like that import {ReactComponent as MyIcon} from "build/icons/my-icon.svg";, but still say "Can't resolve 'build/icons/my-icon.svg'", any idea?
Screenshot:
you need to use file-loader
and when you import dont use brackets since its default export just chose the name directly
import myIcon from "build/icons/my-icon.svg";
const App = () => {
return (
<div className="App">
<img src={myIcon} />
</div>
);
}
Svg tag
second option would be to extract the svg tag and put it directly into you component ,
const App = () => {
return (
<div className="App">
<svg .... // copy the content of your .svg
</svg>
</div>
);
}

Build an Image slider in react

I can't figure out something very simple :-(
I'm building an image slider in react, with this idea:
Import a data.js file, containing the image filepaths.
the user clicks on a button and moves through the array.
Of course, I cant import images one by one...
import React from 'react';
import pics from './data'; //-->array with paths to images.
function App() {
let path =`./wallpapers/${pics[0]}`
console.log(path)
return (
<div className="App">
<img className='image' src={path} alt='dont know how will fix this, we dont have a way to generate alt content'/>
<div className='panel'>
<button>Left</button>
<button>Right</button>
</div>
</div>
);
}
export default App;
Now I'm confused since as this is javascript images won't be loaded like that. Is there any way to achieve this, or any technology I should take a look at?
You would need some sort of "current" image setting. Clicking the buttons would trigger the value to up or down. Default it to 0. This code isn't going to work as is, but the concept is like this:
import React, { useState } from 'react'
import wallpapers from './wallpapers'
function App() {
[ currentImage, setCurrentImage ] = useState(0)
const path =`./wallpapers/${wallpapers[currentImage]}`
return (
<div className="App">
<img className='image' src={path} alt='dont know how will fix this, we dont have a way to generate alt content'/>
<div className='panel'>
<button onClick={() => setCurrentImage(currentImage - 1)}>Left</button>
<button onClick={() => setCurrentImage(currentImage + 1)}>Right</button>
</div>
</div>
);
}
In a separate file, you can import all the images
// wallpapers/index.js
import Wall1 from './wallpapers/1.png';
import Wall2 from './wallpapers/2.png';
import Wall3 from './wallpapers/3.png';
import Wall4 from './wallpapers/4.png';
import Wall5 from './wallpapers/5.png';
import Wall6 from './wallpapers/6.png';
export default [
Wall1,
Wall2,
Wall3,
Wall4,
Wall5,
Wall6
]

React dynamically add image

I am trying to add images dynamically from the assets folder in my react component. This is the code that I have:
import React from 'react';
const card = (props) => {
const image = require.context(
`../../assets/imgs`,
true,
new RegExp(`(${props.vnum}_${props.snum}.png)$`)
);
return (
<div>
<img src={image} alt="image" />
<p>{props.english}</p>
<p>{props.french}</p>
</div>
);
};
When I do this, I get the following error:
TypeError: webpack_require(...).context is not a function
I used CRA and looking up past posts I see that this should work. Where am I going wrong?
This should be enough.
import React from 'react';
const Card = (props) => {
return (
<div>
<img alt="image" src={require(`../../assets/imgs/${props.vnum}_${props.snum}.png`} />
<p>{props.english}</p>
<p>{props.french}</p>
</div>
);
};
It's necessary to use it in those convention?
The simpler solution without require.context()
import React from 'react';
import Image from "../../assets/img/english
import Image from "../../assets/img/french
const card = (props) => {
return (
<div>
<img src={english} alt="image" />
<p>{props.english}</p>
<img src={french} alt="image" />
<p>{props.french}</p>
</div>
);
};
Also:
It's possible to add some conditional rendering here (depends on variable render english or french) - i'm not sure You need it.
require.context is a special feature supported by webpack's compiler that allows you to get all matching modules starting from some base directory. The intention is to tell webpack at compile time to transform that expression into a dynamic list of all the possible matching module requests that it can resolve, in turn adding them as build dependencies and allowing you to require them at runtime.
So if regex matches more than 1 element - mapping is needed - however i think in this specific issue import is enough.
you can use simply require()
import React from "react";
import "./styles.css";
import Card from "./card";
export default function App() {
return (
<div className="App">
<h1>Hello</h1>
<h2>check this!</h2>
<Card vnum={12} snum={13} english={"english"} />
</div>
);
}
card.js
import React from "react";
export default function card(props) {
const image = require(`./img/${props.vnum}_${props.snum}.jpg`);
return (
<div>
<img src={image} alt="image1" width="200px" />
<p>{props.english}</p>
</div>
);
}
you can check this at here https://codesandbox.io/s/elegant-ramanujan-5qwcp
This is not the exact anser for your question, but might help you in later scenes maybe you may already know about this. If you have got URL's of the image that can be grabbed from internet, then you can save them into an array. Eg: const array = ['url1', 'url2',....etc]
Then use : array.map(url => { <img src={url} /> })
Also if you are pulling from an API use the same method.

How to use a SVG React component as background?

I have SVG files written in Function Components.
import React from "react";
const MySVGBackground= (props) => {
return (
<svg> some svg here</svg>
);
};
export default MySVGBackground;
I need to render this as a background:
<div style={{ backgroundImage: `url(${MySVGBackground})` }}> </div>
but it's not working.
I can't purely import the SVG directly, because it gives me an error of Unexpected Token. So I have to wrap the SVG into the FC and export it.
Here is the sample code:
https://codesandbox.io/s/react-background-issue-9wt4x?file=/src/App.js
Try this:
https://codesandbox.io/s/react-background-issue-ut933
import React from "react";
import "./styles.css";
import BackgroundSVG from "./backgroundSVG";
// import this to render static markup
import { renderToStaticMarkup } from 'react-dom/server';
export default function App() {
// convert component to string useable in data-uri
const svgString = encodeURIComponent(renderToStaticMarkup(<BackgroundSVG />));
return (
<div className="App">
<h2
style={{
backgroundImage: `url("data:image/svg+xml,${svgString}")`
}}
>
Svg background
</h2>
</div>
);
}
The data: image/svg+xml;utf8 part tells the browser that raw image data is following.
More information can be found here:
https://css-tricks.com/lodge/svg/09-svg-data-uris/
https://gist.github.com/iansinnott/2e8fe9d9e4c6c7c55793d38f81c999a3

How to render text in component form <text /> in react?

I want to display text in the form of react component inside react app.
When I tried to render it, it gives me not defined error, which is understandable.
import React from 'react';
import HeaderClass from './Header.css';
import logo from '../../Assets/Images/logo.jpg'
const Header = () => {
return(
<div className="header-wrapper">
<p className="logo__tagline"> <text /> </p>
<img className="App__logo" src={logo} alt="Name" />
</div>
)
};
export default Header;
Not sure exactly what you are trying to do?
But if i understand correct you could do like this:
In the text file:
import React, { Fragment } from 'react'; // So it doesn't create a unnecessary node element. **Only available in react 16+
export const Text = () => <Fragment>Your text here</Fragment>;
and then you can bring in the text element and use it in your code:
import React from 'react';
import HeaderClass from './Header.css';
import logo from '../../Assets/Images/logo.jpg'
import { Text } from './Text'
const Header = () => {
return(
<div className="header-wrapper">
<p className="logo__tagline"> <Text /> </p>
<img className="App__logo" src={logo} alt="Name" />
</div>
)
};
export default Header;
Maybe i have misunderstood the question but i don't know why you would want to do this.

Resources