Issue with React: Caret icon in dropdown menu shifts position when page is resized to iPad or smaller dimensions

I'm facing an issue with a styled react component that has a custom dropdown menu featuring a caret icon. Whenever I test the responsiveness of the dropdown, the caret icon ends up outside the intended area. To resolve this, I've wrapped the dropdown inside a larger component to ensure everything is on the same line. Additionally, I included the icon within the styled select component. It's puzzling because I've used a similar approach in another application and didn't encounter any problems with icon placement. Any suggestions or help would be greatly appreciated.

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { FaCaretDown } from 'react-icons/fa'
import Table from '../core/Table'
import SubHeader from '../elements/SubHeader'
import EligibleOffer from './EligibleOffer'
import { tableDataProps, tableColumnProps } from '../../propTypes'

const BUNDLE_KEY = 'bundle'
const rowKey = 'id'

class OfferBundlesTable extends Component {
  static propTypes = {
    bundles: PropTypes.arrayOf(tableDataProps),
    columns: tableColumnProps,
    viewedOfferIds: PropTypes.arrayOf(PropTypes.string),
    onBundleSelect: PropTypes.func
  }

  static defaultProps = {
    viewedOfferIds: []
  }

  renderCell = (cell = {}) => (
    <div>
      {cell.title && <SubHeader>{cell.title}</SubHeader>}
      <p>{cell.details}</p>
    </div>
  )

  renderBundle = bundle => (
    <StyledOffer
      offer={bundle}
      onOfferSelect={this.props.onBundleSelect}
      viewed={this.props.viewedOfferIds.includes(bundle.OfferId)}
    />
  )

  getColumns = columns =>
    Object.entries(columns).reduce(
      (cols, [key, value]) => ({
        ...cols,
        [key]: {
          ...value,
          renderCell: key === BUNDLE_KEY ? this.renderBundle : this.renderCell
        }
      }),
      {}
    )

  render() {
    const { bundles = [], columns = [] } = this.props

    return (
      <div>
        <DropdownRow>
          <StyledSelect>
            <StyledStrong>SORT BY: </StyledStrong>
            <select>
              <option>Default</option>
              <option>Promo Price (High to Low)</option>
              <option>Promo Price (Low to High)</option>
              <option>Alphabetically (A-Z)</option>
              <option>Alphabetically (Z-A)</option>
              <option>Internet Tier (High to Low)</option>
              <option>Internet Tier (Low to High)</option>
            </select>
            <StyledSelectIcon size="1.5rem" />
          </StyledSelect>
          <StyledSelect>
            <StyledStrong>CONTRACT TERMS (MONTHS):</StyledStrong>
            <select>
              <option>36</option>
              <option>24</option>
              <option>12</option>
            </select>
            <StyledSelectIcon size="1.5rem" />
          </StyledSelect>
        </DropdownRow>
        <StyledTable
          rowKey={rowKey}
          rows={bundles}
          columns={this.getColumns(columns)}
        />
      </div>
    )
  }
}

const StyledTable = styled(Table)`
  th:first-child {
    width: 25%;
  }
`

const StyledOffer = styled(EligibleOffer)`
  margin-bottom: 15px;
`

const DropdownRow = styled.div`
    th:first-child {
    width: 25%;
  } 

  flex: 1;
  display: flex;
  align-items: stretch;
  padding: 20px 30px 20px 10px;
  width: 60%;
  margin-left: 42%;
`

const StyledSelectIcon = styled(FaCaretDown)`
  position: absolute;
  top: 0;
  right: 10px;
  bottom: 0;
  margin: auto;
  color: black;
  pointer-events: none;
`

const StyledSelect = styled.div`
  position: relative;
  margin-left: auto;


  select {
    padding: 5px 45px 5px 10px;
    font-size: 1.2rem;
    line-height: 1.4rem;
    font-weight: 500;
    color: black;
    border: 2px solid black;
    height: 36px;
    appearance: none;
    background: transparent;
    border-radius: 0;
  }
`

const StyledStrong = styled.strong`
  padding-right: 5px;
`

export default OfferBundlesTable

Answer №1

Upon reviewing your code, I recommend a different approach, which involves adding the caret in the CSS for your select element. This ensures that the caret remains attached to the select element and cannot move independently. You can test this functionality by running the snippet provided below. Ideally, you should integrate this into the styled-component CSS definition and eliminate the need for the <StyledSelectIcon/> altogether. Here's a forked Stackblitz for reference: (link).

Definition of Styled Component:

const StyledSelect = styled.div`
  position: relative;
  margin-left: auto;

  select {
    padding: 5px 45px 5px 10px;
    font-size: 1.2rem;
    line-height: 1.4rem;
    font-weight: 500;
    color: black;
    border: 2px solid black;
    height: 36px;
    background-color: transparent;
    border-radius: 0;
    -moz-appearance: none;
    -webkit-appearance:none;
    appearance: none;
    background-image: url('data:image/svg+xml;utf8,<svg fill="black" viewBox="0 0 320 512" height="1.5rem" width="1.5rem" xmlns="http://www.w3.org/2000/svg"><path d="M31.3 192h257.3c17.8 0 26.7 21.5 14.1 34.1L174.1 354.8c-7.8 7.8-20.5 7.8-28.3 0L17.2 226.1C4.6 213.5 13.5 192 31.3 192z"></path></svg>');
    background-repeat: no-repeat;
    background-position: right 8px center;
  }
`

Run the Snippet Below:

.customselect{
  padding: 5px 45px 5px 10px;
  font-size: 1.2rem;
  line-height: 1.4rem;
  font-weight: 500;
  color: black;
  border: 2px solid black;
  height: 36px;
  background-color: transparent;
  border-radius: 0;
  -moz-appearance: none;
  -webkit-appearance:none;
  appearance: none;
  background-image: url('data:image/svg+xml;utf8,<svg fill="black" viewBox="0 0 320 512" height="1.5rem" width="1.5rem" xmlns="http://www.w3.org/2000/svg"><path d="M31.3 192h257.3c17.8 0 26.7 21.5 14.1 34.1L174.1 354.8c-7.8 7.8-20.5 7.8-28.3 0L17.2 226.1C4.6 213.5 13.5 192 31.3 192z"></path></svg>');
  background-repeat: no-repeat;
  background-position: right 8px center;
}
<select class="customselect">
  <option>Option A</option>
  <option>Option B</option>
  <option>Option C</option>
  <option>Option D</option>
</select>

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

Exploring the functionality of Jquery with the :active selector

Here is the code I have been working on: $('#ss a:active').parent().addClass('ss-active'); It seems like my code is not functioning as expected. Can you help me figure out how to achieve my desired outcome? Additionally, I want the bu ...

Manage specific Disclosures with Headless UI Open/Close functionality

I need some help figuring out how to control specific Headless UI Disclosures. Currently, when I open one disclosure, the others also open simultaneously. Here is the current situation: https://i.sstatic.net/c65jT.png What I want to achieve is that when ...

Steps to resolve the issue: The 'jsx' functionality is not activated at the moment

I recently started working with ReactJS and I came across a similar error message in this post: Syntax Error: Support for the experimental syntax 'jsx' isn't currently enabled. Despite reading it, I am still unable to solve my issue. When I ...

Issues with using a personalized font in a Stenciljs project

Looking for guidance on implementing a custom font in my Stenciljs app. I have the otf file, unsure if an npm package is necessary. Here's my code: filestructure: -src --components --assets ---Anurti-Regular.tiff ---Anurti-Regular.ttf friends-l ...

Simplified jQuery function for multiple div mouseover operations

Uncertain about the accuracy of my title. Due to certain reasons, I need to assign different IDs for the class, as it only detects ID and not class when hovered over. Therefore, I have created a CSS version where the opacity of a specific div will change t ...

The issue with the Hidden Content feature in the Slick Carousel is that it does not function correctly on the

There are some related topics worth exploring, such as: Slick carousel center class not working when going from last item to first item Despite trying various solutions, the issue still persists in my code. My goal is to have each item displayed in the ce ...

The clerk and next.js authentication middleware code falls short in securing my /dashboard route effectively

My dashboard route isn't authenticating properly before entering. I have both my .env and middleware files located outside the app folder. import { authMiddleware } from "@clerk/nextjs"; export default authMiddleware({ // Routes that c ...

Using jQuery to replace the content of a div with a delay?

I am attempting to utilize jQuery to create a fade effect on an element, replace its innerHTML content, and then fade it back in once the new content has been added. I have successfully managed to replace the element's content using the .html() method ...

Contrast in colors: Comparing three.js with vanilla JavaScript to react-three-fiber with create-react-app

For some time now, I've been puzzled by the difference in material colors between react-three-fiber and threejs. The colors in react-three-fiber seem duller compared to threejs. Both implementations use the same objects and properties. The threejs ve ...

Is it possible to have a never-ending slideshow with inline-blocks?

After spending countless hours trying to troubleshoot my code, I am now seeking help from the wonderful people of the internet! ;) It seems like only a small portion of my code is incorrect. What I'm attempting to do is move the leftmost object in the ...

Sliding through HTML content

Unfortunately, I lack expertise in advanced HTML and CSS. After some investigation, I attempted to create a "content slider" similar to the one on the Redlight Traffic website (an anti-human trafficking organization). However, my efforts have been unsucces ...

Hide the background when the modal appears

I have successfully implemented a jQuery CustomBox modal on my website. However, I am facing an issue with hiding the content div behind the modal once it pops up. My goal is to make the content div reappear after the modal has been closed. You can view a ...

Unable to upload code onto GitHub due to the excessive size of node modules

I recently restructured my react project, separating the front-end code into a client directory while keeping the back-end code in the root directory. However, I encountered an issue when trying to push my code to GitHub. An error message indicated that th ...

Steer your keyboard attention towards the parent element that embodies a list

My implementation focuses on making drop down menus accessible via keyboard input using HTML/CSS and JS/jQuery events. The goal of keyboard accessibility includes: Tab key to navigate the menu elements. Pressing the down arrow key opens a focused menu. ...

How can I make col-8 and col-4 display next to each other?

Here is the code snippet I recently submitted: <section class="main-container"> <div class="grid-row no-gutters"> <div class="column-8"> <img class="full-width-img& ...

Tips on resolving the issue of an Axios post request not appearing in a get request in React

When using axios to make a post request in this code, a new username is posted, but there is an issue with retrieving the posted name from the API. How can I fix this problem to view my posted request? const App = () => { const [data, setData] = u ...

What is the process for connecting a personalized bootstrap framework with an index.html document?

I have recently dived into the world of bootstrap and I just customized my bootstrap file on http://getbootstrap.com/docs/3.3/customize/ After compiling and downloading, I found it challenging to link it with my index.html file. The source of the bootstra ...

When using React JS to sign in with LinkedIn, users are redirected to a 404 error page on a hosted website but not when testing

I've been working on a React JS application and attempting to incorporate Signin with LinkedIn. The functionality works perfectly on my localhost, but when I deploy the app online, a popup appears, I log in, and then it redirects to a 404 page with th ...

Unable to integrate React-Bootstrap with Expo due to an error resolving the module react/jsx-runtime

Working on a react-Native app with Expo, I decided to utilize components from the bootstrap library. I kicked off a new project: expo init test-app Next, I integrated the library into the project folder: expo install react-bootstrap@next <a href="/cdn- ...

Display a preview of a React component

Currently facing a challenge where I need to create a form for users to adjust the title, background color, button background, text color, and other settings of a component. I want to provide a live preview of the component as the user makes changes. I en ...