Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Crear un visor de imágenes (carrusel) con React

Tiempo de lectura: 2 minutos

Este tutorial utiliza React y CSS para crear un carrusel simple y funcional.

Paso 1: Configurar el entorno de React

Si aún no tienes una aplicación de React configurada, primero necesitas crear una. Si ya la tienes, puedes saltarte este paso.

  1. Instalar create-react-app:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npx create-react-app carrusel-imagenes
cd carrusel-imagenes
npx create-react-app carrusel-imagenes cd carrusel-imagenes
   npx create-react-app carrusel-imagenes
   cd carrusel-imagenes
  1. Iniciar la aplicación:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm start
npm start
   npm start

Paso 2: Crear la estructura del carrusel

  1. Crear el componente Carousel: Crea un archivo nuevo llamado Carousel.js en el directorio src/components (debes crear la carpeta components si no existe).
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// src/components/Carousel.js
import React, { useState } from 'react';
import './Carousel.css'; // Agregaremos el CSS en el siguiente paso
const images = [
'https://via.placeholder.com/600x300?text=Image+1',
'https://via.placeholder.com/600x300?text=Image+2',
'https://via.placeholder.com/600x300?text=Image+3'
];
const Carousel = () => {
const [currentIndex, setCurrentIndex] = useState(0);
const goToPrevious = () => {
const isFirstSlide = currentIndex === 0;
const newIndex = isFirstSlide ? images.length - 1 : currentIndex - 1;
setCurrentIndex(newIndex);
};
const goToNext = () => {
const isLastSlide = currentIndex === images.length - 1;
const newIndex = isLastSlide ? 0 : currentIndex + 1;
setCurrentIndex(newIndex);
};
return (
<div className="carousel">
<div className="carousel-inner">
<img src={images[currentIndex]} alt={`Slide ${currentIndex}`} />
</div>
<button className="carousel-button prev" onClick={goToPrevious}></button>
<button className="carousel-button next" onClick={goToNext}></button>
</div>
);
};
export default Carousel;
// src/components/Carousel.js import React, { useState } from 'react'; import './Carousel.css'; // Agregaremos el CSS en el siguiente paso const images = [ 'https://via.placeholder.com/600x300?text=Image+1', 'https://via.placeholder.com/600x300?text=Image+2', 'https://via.placeholder.com/600x300?text=Image+3' ]; const Carousel = () => { const [currentIndex, setCurrentIndex] = useState(0); const goToPrevious = () => { const isFirstSlide = currentIndex === 0; const newIndex = isFirstSlide ? images.length - 1 : currentIndex - 1; setCurrentIndex(newIndex); }; const goToNext = () => { const isLastSlide = currentIndex === images.length - 1; const newIndex = isLastSlide ? 0 : currentIndex + 1; setCurrentIndex(newIndex); }; return ( <div className="carousel"> <div className="carousel-inner"> <img src={images[currentIndex]} alt={`Slide ${currentIndex}`} /> </div> <button className="carousel-button prev" onClick={goToPrevious}>❮</button> <button className="carousel-button next" onClick={goToNext}>❯</button> </div> ); }; export default Carousel;
   // src/components/Carousel.js
   import React, { useState } from 'react';
   import './Carousel.css'; // Agregaremos el CSS en el siguiente paso

   const images = [
     'https://via.placeholder.com/600x300?text=Image+1',
     'https://via.placeholder.com/600x300?text=Image+2',
     'https://via.placeholder.com/600x300?text=Image+3'
   ];

   const Carousel = () => {
     const [currentIndex, setCurrentIndex] = useState(0);

     const goToPrevious = () => {
       const isFirstSlide = currentIndex === 0;
       const newIndex = isFirstSlide ? images.length - 1 : currentIndex - 1;
       setCurrentIndex(newIndex);
     };

     const goToNext = () => {
       const isLastSlide = currentIndex === images.length - 1;
       const newIndex = isLastSlide ? 0 : currentIndex + 1;
       setCurrentIndex(newIndex);
     };

     return (
       <div className="carousel">
         <div className="carousel-inner">
           <img src={images[currentIndex]} alt={`Slide ${currentIndex}`} />
         </div>
         <button className="carousel-button prev" onClick={goToPrevious}>❮</button>
         <button className="carousel-button next" onClick={goToNext}>❯</button>
       </div>
     );
   };

   export default Carousel;
  1. Agregar el CSS para el carrusel: Crea un archivo CSS llamado Carousel.css en el directorio src/components.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
/* src/components/Carousel.css */
.carousel {
position: relative;
width: 600px;
margin: auto;
overflow: hidden;
}
.carousel-inner {
display: flex;
transition: transform 0.5s ease-in-out;
}
.carousel-inner img {
width: 100%;
}
.carousel-button {
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: rgba(0, 0, 0, 0.5);
border: none;
color: white;
font-size: 2rem;
cursor: pointer;
}
.carousel-button.prev {
left: 10px;
}
.carousel-button.next {
right: 10px;
}
/* src/components/Carousel.css */ .carousel { position: relative; width: 600px; margin: auto; overflow: hidden; } .carousel-inner { display: flex; transition: transform 0.5s ease-in-out; } .carousel-inner img { width: 100%; } .carousel-button { position: absolute; top: 50%; transform: translateY(-50%); background-color: rgba(0, 0, 0, 0.5); border: none; color: white; font-size: 2rem; cursor: pointer; } .carousel-button.prev { left: 10px; } .carousel-button.next { right: 10px; }
   /* src/components/Carousel.css */
   .carousel {
     position: relative;
     width: 600px;
     margin: auto;
     overflow: hidden;
   }

   .carousel-inner {
     display: flex;
     transition: transform 0.5s ease-in-out;
   }

   .carousel-inner img {
     width: 100%;
   }

   .carousel-button {
     position: absolute;
     top: 50%;
     transform: translateY(-50%);
     background-color: rgba(0, 0, 0, 0.5);
     border: none;
     color: white;
     font-size: 2rem;
     cursor: pointer;
   }

   .carousel-button.prev {
     left: 10px;
   }

   .carousel-button.next {
     right: 10px;
   }

Paso 3: Usar el componente Carousel en la aplicación principal

  1. Modificar App.js para incluir el carrusel:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// src/App.js
import React from 'react';
import Carousel from './components/Carousel';
import './App.css';
function App() {
return (
<div className="App">
<h1>Carrusel de Imágenes con React</h1>
<Carousel />
</div>
);
}
export default App;
// src/App.js import React from 'react'; import Carousel from './components/Carousel'; import './App.css'; function App() { return ( <div className="App"> <h1>Carrusel de Imágenes con React</h1> <Carousel /> </div> ); } export default App;
   // src/App.js
   import React from 'react';
   import Carousel from './components/Carousel';
   import './App.css';

   function App() {
     return (
       <div className="App">
         <h1>Carrusel de Imágenes con React</h1>
         <Carousel />
       </div>
     );
   }

   export default App;
  1. Agregar algunos estilos básicos en App.css:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
/* src/App.css */
.App {
text-align: center;
}
.App h1 {
margin-top: 20px;
}
/* src/App.css */ .App { text-align: center; } .App h1 { margin-top: 20px; }
   /* src/App.css */
   .App {
     text-align: center;
   }

   .App h1 {
     margin-top: 20px;
   }

Paso 4: Ejecutar la aplicación

Asegúrate de que tu servidor de desarrollo esté funcionando. Si lo detuviste, vuelve a iniciarlo con:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm start
npm start
npm start

Abre tu navegador y navega a http://localhost:3000. Deberías ver tu carrusel de imágenes en funcionamiento.

Resultado:

0

Deja un comentario