Flexbox element in React not resizing to fit width

I've been working on a slide carousel and it's almost complete, but I'm facing an issue with adjusting the arrows to the images.

When testing the website for responsiveness, I noticed that the div inside the flexbox stops shrinking and remains in one position. While this may look okay due to overflow: hidden, the arrows stay static in position and end up disappearing.

The challenge lies in making sure that the arrows are still accessible even when the website is viewed at smaller resolutions.

I hope I have provided enough detail about the problem.

CSS:

.header{
    display: flex;
    position: relative;
    justify-content: center;
    align-items: center;
    flex-basis: 100%;
    height: 40vh;
    border-color: white;
    overflow: hidden;
}

.header__box{
}

.right-arrow{ 
position: relative;
bottom: 350px;
left: 900px;
 font-size: 2rem;
 color: #000;
 z-index: 10;
 cursor: pointer;
 user-select: none;
}

.left-arrow{
    position: relative;
    bottom: 350px;
    left: 80px;
    font-size: 2rem;
    color: #000;
    z-index: 10;
    cursor: pointer;
    user-select: none;
}

.slide{
    opacity: 0;
    transition-duration: 1s;
    transform: scale(1.00);
}

.slide.active{
    display: flex;
    flex-basis: 100%;
    opacity: 1;
    transition-duration: 1s;
    transform: scale(1.00);
}

.image{
}

Code:

import React, {useState} from 'react';
import './Header.css';
import {HeaderData} from './HeaderData'
import {FaArrowAltCircleRight, FaArrowAltCircleLeft} from 'react-icons/fa'

const Header = ({slides}) => {
    const [current, setCurrent] = useState(0)
    const length = slides.length

    const nextSlide = () => {
        setCurrent(current === length - 1 ? 0 : current + 1)
    }

    const prevSlide = () => {
        setCurrent(current === 0? length -1 : current -1 )
    }

    console.log(current)

    return (
    <div className='header'> 
        <div className='header__box'>
            {HeaderData.map((slide, index) => {
                    return (
                        <div className={index === current? 'slide active' : 'slide'}>
                            {index === current ? <img src={slide.image} className='image' alt='shoe photo'/> : null}
                        </div>
                        
                    )
            })}
             <FaArrowAltCircleLeft className='left-arrow' onClick={prevSlide}/>
            <FaArrowAltCircleRight className='right-arrow' onClick={nextSlide}/>   
            </div>
    </div>
    )
}

export default Header;

Answer №1

Consider implementing a structure like this:

.header {
  display: flex;
  justify-content: center;
  height: 40vh;
  border-color: white;
  overflow: hidden;
}

.header__box {
  display: flex;
  align-items: center;
}

.right-arrow,
.left-arrow {
  font-size: 2rem;
  cursor: pointer;
  user-select: none;
}

.slide {
  opacity: 0;
  transition-duration: 1s;
  transform: scale(1);
}

.slide.active {
  opacity: 1;
  transition-duration: 1s;
  transform: scale(1);
}

img.image {
  padding: 10px;
}

Additionally, you can utilize the following setup:

const Header = ({ slides }) => {
  const [current, setCurrent] = useState(0);
  const length = slides.length
  const HeaderData = [{ image: test }, { image: foto }, { image: foto2 }];

  const nextSlide = () => {
    setCurrent(current === length - 1 ? 0 : current + 1);
  };

  const prevSlide = () => {
    setCurrent(current === 0 ? length - 1 : current - 1);
  };

  return (
    <div className="header">
      <div className="header__box">
        <FaArrowAltCircleLeft className="left-arrow" onClick={prevSlide} />
        {HeaderData.map((slide, index) => {
          return (
            <div className={index === current ? "slide active" : "slide"}>
              {index === current ? (
                <img src={slide.image} className="image" alt="shoe photo" />
              ) : null}
            </div>
          );
        })}
        <FaArrowAltCircleRight className="right-arrow" onClick={nextSlide} />
      </div>
    </div>
  );
};

The concept here is to arrange the slides between the left and right arrows within the designated section.

By structuring the code in the manner shown above, with display: flex applied to the .header__box element enveloping the slides and arrows, positioning the arrows becomes more efficient. Crucially, setting align-items: center on .header__box ensures that the arrows are centrally aligned within the container.

View Sandbox Example

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error Encountered: Unable to utilize $(...).mask function with jQuery in ASP.NET using C#

I have encountered an issue while working on a task involving jQuery masked for date. When running the task in HTML, it works perfectly fine. However, when attempting to run it in ASP.NET, I face the problem where 'mask is not a function'. Below ...

Exploring Material UI's Typography fontSize feature

After upgrading my material UI version from 3.9.4 to 4.11.0, I had to make some changes in the theme style override section to fix certain warnings: https://i.sstatic.net/GjzI9.png https://i.sstatic.net/LVHGk.png However, I encountered a challenge with ap ...

How to Use ngFor to Create a Link for the Last Item in an Array in Angular 7

I need help with adding a link to the last item in my menu items array. Currently, the menu items are generated from a component, but I'm unsure how to make the last item in the array a clickable link. ActionMenuItem.component.html <div *ngIf= ...

Customize Vuetify Menu by adding a unique custom keypad component for editing text fields

I am currently developing an app using vuetify, and I am encountering some challenges with the v-menu feature. The issue arises when I click on a text input field, it triggers the opening of a v-menu. Within this menu, there is a custom component that I h ...

Numerous pie charts created from data retrieved through multiple ajax requests

Hey there! I'm looking to create 3 pie charts side by side, each based on a different dataset retrieved through separate ajax calls. The first chart will be generated from the results of one call, the second from another, and the third from yet anothe ...

Harnessing the power of JavaScript functions to display an image when clicked

Looking for help with making an image appear when clicking on one of three images? Despite trying different approaches, the desired result is still not achieved. I'm aware of using if else statements but exploring other methods. Any insights on what m ...

issues with responsive mobile navigation

Greetings! I've been diligently working on a website project for a client, but I have a nagging feeling that I may have overlooked something important. If you'd like to take a look at the small design mockup preview I'm providing for the cl ...

Conditions must fail for window.location to execute

<a href="www.google.com" class="social" id="social">Click here for Link one</a> <a href="www.cnn.com" class="social" id="social">Visit Link two now!</a> <a href="www.facebook.com" class="social" id="social">This is Link thre ...

Is there a way to show the Username across multiple login pages without using PHP?

Is there a way to dynamically display the username on the Homepage by extracting it from the URL? <div id="login"> <form method="post" action=""> <h2>Login</h2> <p> <label for="username"&g ...

The Angular routing feature seems to be malfunctioning as the URL is showing up but the page fails to load

After including angular.min.js and angular-route.min.js I encountered an issue where clicking the login button would change the URL to '/home', but the home.html page wouldn't load. I attempted adding a controller under templateUrl, but it ...

I'm unable to modify the text within my child component - what's the reason behind this limitation?

I created a Single File Component to display something, here is the code <template> <el-link type="primary" @click="test()" >{{this.contentShow}}</el-link> </template> <script lang="ts"> imp ...

Generating a JSON document from a collection of text files

I have a question about JSON files and bash scripting: My goal is to create a JSON file that contains two keys, "key1" and "key2", each with multiple values stored in separate .txt files. The contents of the .txt files for each key are structured like thi ...

Encountering the issue of receiving an undefined value for a variable despite having previously defined it within

I’ve been working on implementing the Google Maps distance matrix API with the google-distance-matrix library. Here’s the code snippet I’m using: app.get("/users", (req, res) => { // console.log(req.query); // res.send(req.query); ...

Empty req.params in nested ExpressJS routers

I have a unique routing system that relies on the directory structure of my 'api' folder to automatically configure routes. However, I encountered an issue where the req.params object is undefined in the controller when using a folder name as a r ...

Ways to Implement Horizontal Scrolling in Dojo FilteringSelect Component

The select field on my form contains option values that are over 250 characters long, making it difficult for users to read them within the select box. Is there a solution to make the select field scroll horizontally or wrap the lengthy text? ...

Looking for a JavaScript code to create a text link that says "submit"?

Here is the code I have, where I want to utilize a hyperlink to submit my form: <form name="form_signup" id="form_signup" method="post" action="/" enctype="multipart/form-data"> ... <input type="submit" value="Go to Step 2" name="completed" /> ...

How can I retrieve array responses for multiple HTML elements using a single AJAX call in PHP with Ajax post?

See page <button id='comparison_button'>Compare</button> <div id="sourceResponse"></div> <div id="destResponse"></div> <div id="missingResponse"></div> JS $(document).ready(function(){ $(&apo ...

Error: AJAX encountered an unexpected token

An error message has appeared stating: Uncaught SyntaxError: Unexpected token : This error relates to the following line of code: data: userCoupon: $('#couponCode').val(), Here is the script in question: $(function() { $("#signInButton2"). ...

I am unable to access the property of the ReactJs object

I'm encountering an issue while trying to pass a variable into JSX within the render section of my React JS script. The error message I'm receiving is Cannot read property 'title' of undefined. Even though I have defined this property ...

Positioning a DIV in the center within Bootstrap columns

I have been attempting to solve the challenge of vertically aligning content within my bootstrap grid. Within my 3 col-md-4 columns, I am looking to center another div along with text inside each of them. This is the current appearance: https://i.sstati ...