Build an Image slider in react - reactjs

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
]

Related

Image not getting displayed in react project

This is my App.js. Here, I call the "Profile" Component.
import './App.css';
import Profile from "./Profile"
function App() {
return (
<div className="App">
<Profile />
</div>
);
}
export default App;
Then, inside Profile.js, I call Card component and inside the Card component, I've enclosed an image.
import React from 'react'
import Card from './Card'
import styles from "./Profile.module.css"
import image1 from "./assets/profile1.png"
const Profile = () => {
return (
<Card>
<div>
<img src={image1} alt="" />
</div>
</Card>
)
}
export default Profile
Inside of Card component, I've just applied some CSS to make it look like a Card.
import React from 'react'
import styles from "./Card.module.css"
const Card = () => {
return (
<div className={styles.card}>
</div>
)
}export default Card
This is my folder structure.
I'm really confused why the image isn't getting showed up. Currently this is the output I'm getting.
I've restarted the server as well. But it's not getting fixed.
your card doesn't have a child component return maybe that could be the problem
import React from 'react'
import styles from "./Card.module.css"
const Card = ({children}) => {
return (
<div className={styles.card}>
{children}
</div>
)
}
export default Card
try this

React -- Mapping specific images to specific cards

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.

I am facing problem using Simple React Lightbox Next js?

I am building nextjs application. I want a lightbox feature that only show a button, then when I click the button it show the lightbox gallery. But default or on page load there should not be show images. Just when I click a button it show light box. Like when I clicked the button-
Then It start lightbox-
How can I do that?
Here I am trying to use Simple React LightBox. This package support hook. But there are not well documented to understand how to use hook. First Of all I create a button and then I create a lightbox component. Like this-
import {Container, Flex, Box, Image, Paragraph} from "theme-ui";
import SingleRooms from "data/SingleRooms";
import SimpleReactLightbox, {SRLWrapper, useLightbox} from "simple-react-lightbox";
const SingleImages = () => {
const {openLightbox, closeLightbox} = useLightbox()
return (
<Container>
<button onClick={() => openLightbox()}>
Open the third image
</button>
<SimpleReactLightbox>
<SRLWrapper>
<a href={SingleRooms.images[0].path}>
<img src={SingleRooms.images[0].path} alt="Umbrella"/>
</a>
<a href={SingleRooms.images[1].path}>
<img src={SingleRooms.images[1].path} alt="Blue sky"/>
</a>
</SRLWrapper>
</SimpleReactLightbox>
</Container>
);
};
export default SingleImages;
It is not working. Actually I don't know to use it. Please help me to use it with my wanted options. Just show a button then when clicked button there should be show the light box. Please help me.
According to the simple-react-lightbox documentation:
First of all you need to wrap your React app with the main component so that it can create the context.
So in your top-level (root/main/index) component:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import SimpleReactLightbox from 'simple-react-lightbox'
ReactDOM.render(
<React.StrictMode>
<SimpleReactLightbox> // ----> here
<App />
</SimpleReactLightbox>
</React.StrictMode>,
document.getElementById("root")
);
export default App;
Now, in the SingleImages component:
import {Container, Flex, Box, Image, Paragraph} from "theme-ui";
import SingleRooms from "data/SingleRooms";
import {SRLWrapper, useLightbox} from "simple-react-lightbox";
const SingleImages = () => {
const {openLightbox, closeLightbox} = useLightbox()
return (
<Container>
<button onClick={() => openLightbox()}>
Open the third image
</button>
<SRLWrapper>
<a href={SingleRooms.images[0].path}>
<img src={SingleRooms.images[0].path} alt="Umbrella"/>
</a>
<a href={SingleRooms.images[1].path}>
<img src={SingleRooms.images[1].path} alt="Blue sky"/>
</a>
</SRLWrapper>
</Container>
);
};
export default SingleImages;

How to display multiple images with uploaded file URL's?

I am working on a project that uploads images to Heroku with their new react-simple-file-upload addon. After uploading the file, a URL is provided for the image saved in the DB. I managed to display one of the images, but now I would like to display multiple-- essentially create a simple gallery. I am thinking i'll have to make a function that uses useState and an array, but am not really sure how to design it beyond that. Here is my working code:
import React from "react";
import SimpleFileUpload, { SimpleFileUploadProvider } from "../components/SimpleFileUpload"
import { useState } from 'react'
import "./styles.css"
const API_KEY = '...'
export default function About() {
const [files, setFiles] = useState();
console.log(files)
return (
<div className="App">
<h1>upload an image</h1>
<SimpleFileUpload apiKey={API_KEY} onSuccess={setFiles} />
{files && (
<div>
<img className="photo" src={files} witdh="50" hight="50" alt="huh?"/>
<div className="gallery">
</div>
</div>
)}
</div>
);
}
Any tips or tricks is greatly appreciated

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.

Resources