In this tutorial, I'll cover how to build a simple image slider in React js. In this project without using any additional external packages.

Simple Carousel in React js

React image gallery lightbox

Setup

Create your react project. In your terminal/command line enter:

npx create-react-app image-slider
cd image-slider
npm start 

Next, Project structure your folder as follows.

src
├── App.css
├── App.js
├── App.test.js
├── ImageSlider.js
├── index.css
├── index.js
├── reportWebVitals.js
└── setupTests.js 

Next, open up the App.js file located in the src folder. You should see this:

App.js
import React, {useState, useEffect} from 'react'; import axios from 'axios'; import ImageSlider from './ImageSlider'; import './App.css'; function App() { const [isLoading, setLoading] = useState(false) const [isError, setError] = useState(false) const [isdata, setData] = useState({}); const [allimage, setimage] = useState({}); useEffect(() => { fetchData(); }, []); const fetchData = async () => { try { setError(false); axios.get("http://localhost:8080/ViewImage") .then(res => { // then print response status if(res.data.success === true){ setData(res.data.listall); const images = res.data.listall.map((itemall) => (itemall.image)); setimage(images) setLoading(true); } }) } catch (error) { setError(true); } }; return (<> {isError && <div>Something went wrong ...</div>} <div className="banners"> {isLoading === false ? ( <div>Loading ...</div> ) : ( <> <ImageSlider images={allimage} alldata={isdata}/> </> )} </div> {/* Json output */} <pre>{JSON.stringify(isdata, null, 2)} </pre> </> ); } export default App;
ImageSlider.js
import React, { useState } from "react"; const ImageSlider = ({ images,alldata }) => { // takes in images as props const [index, setIndex] = useState(0); // create state to keep track of images index, set the default index to 0 const slideRight = () => { setIndex((index + 1) % images.length); // increases index by 1 }; const slideLeft = () => { const nextIndex = index - 1; if (nextIndex < 0) { setIndex(images.length - 1); // returns last index of images array if index is less than 0 } else { setIndex(nextIndex); } }; return (<> {images.length > 0 && ( <div> <button onClick={slideLeft} className="left-arrow">{"<"}</button> <h1>{alldata[index].title}</h1> <img src={images[index]} alt={index} /> <button onClick={slideRight} className="right-arrow">{">"}</button> </div> )} </> ); }; export default ImageSlider;

React slider fetch title and images into the MySQL database

In the following example, we will start how to React slider fetch title and images into the MySQL database using Node js.

  • Database Name – codeat21
  • Table Name – posts
codeat21
CREATE TABLE `posts` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `image` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Next, Node js project structure your folder as follows.

├── config
|  ├── database.js	  
├── database.js
├── index.js
├── package.js
└── package-lock.js 
database.js
const util = require('util'); const mysql = require('mysql2'); const pool = mysql.createPool({ connectionLimit: 10, host : 'localhost', user : 'root', password : '', database : 'codeat21' }); // Ping database to check for common exception errors. pool.getConnection((err, connection) => { if (err) { if (err.code === 'PROTOCOL_CONNECTION_LOST') { console.error('Database connection was closed.'); } if (err.code === 'ER_CON_COUNT_ERROR') { console.error('Database has too many connections.'); } if (err.code === 'ECONNREFUSED') { console.error('Database connection was refused.'); } } if (connection) connection.release(); return; }); // Promisify for Node.js async/await. pool.query = util.promisify(pool.query); module.exports = pool;
index.js
const express = require('express'); const app = express(); const path = require('path'); const cors = require('cors'); const port = process.env.PORT || 8080; // Databse Connection const db_connection = require('./config/database').promise(); app.use(cors()); app.get('/ViewImage', async (req, res) => { try { const [rows] = await db_connection.execute("SELECT * FROM posts "); return res.json({ success: true, listall:rows, }); } catch (err) {console.log(err)} }); app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))