Pass on styling properties to children components in React and implement them within a CSS stylesheet

Currently, I am utilizing the Dropdown component to mimic an HTML dropdown functionality. However, this component is actually comprised of divs, ordered lists, and unordered lists. My challenge lies in applying styles to specific elements with className attributes from the parent component while rendering the dropdown.css file that contains the necessary styles. I am unsure about the method to target these elements accurately. How can I apply styles to

div className="select-box-current"

using

style={{ border: "1px solid #D4D4D4" }}

and

div className="select-box-list"

with

style={{
          opacity: 1,
          display: "inherit",
          animationName: "none",
          cursor: "pointer"
        }}

You can find the relevant CodeSandblox link here -> https://codesandbox.io/s/weathered-wood-cf8u8?file=/src/App.js:481-614

Answer №1

When working with React, passing props with the same name will result in only the last one being selected. It's recommended to use unique and descriptive names for style props, rather than just "style," to avoid confusion and maintain clarity.

To differentiate between two different styles, assign unique names in the App.js file:

<div className="App">
  <Dropdown
    inputName="viola"
    list={[
      { yard_id: "1", yard_name: "Yard 1" },
      { yard_id: "2", yard_name: "Yard 2" }
    ]}
    // this style is for  className="select-box-current"
    currentStyles={{ border: "1px solid #D4D4D4" }}
    // this style is for className="select-box-list"
    listStyles={{
      opacity: 1,
      display: "inherit",
      animationName: "none",
      cursor: "pointer"
    }}
  />
</div>

Next, pass these props through your component tree in the Dropdown.js file.

Before delving into prop passing, there's an issue that needs mentioning, albeit not directly related.

export const Dropdown = ({ list, ...others }) => {
  const copiedProps = {};
  Object.keys(others).forEach((key) => {
    // These are the props that need to be passed through:
    if ("style" === key || "className" === key) {
      copiedProps[key] = others[key];
    }
  });

  ...

The unnecessary copying of props can actually be counterproductive. Directly access specific incoming props (e.g., props.myProp or other.style) or utilize destructuring assignment.

To accommodate only passing the necessary props, utilize destructuring assignment as shown below:

export const Dropdown = ({
  list,
  currentStyles,
  listStyles,
  className,
  ...others
}) => { ... }

Once the required props are specified, proceed to pass them into the DropdownView, where the targeted elements reside.

<DropdownView
  dropdownItems={dropdownItems}
  activeItem={activeItem}
  hover={hover}
  setActiveItem={(activeItem) => {
    setActiveItem(activeItem);
  }}
  onMouseOver={(hover) => onMouseOver(hover)}
  toggleList={() => toggleList(!hideList)}
  hideList={hideList}
  className={className}
  currentStyles={currentStyles}
  listStyles={listStyles}
/>

After placing the styles and classname appropriately, set them on the desired elements by retrieving and applying the props as demonstrated earlier.

<div
  className="select-box-current"
  tabIndex="0"
  autoFocus={true}
  onClick={() => toggleList()}
  style={currentStyles}
>...</div>

A working example is available through the provided sandbox link. Note that the className prop in DropdowView was not utilized due to ambiguity regarding its intended element.

https://codesandbox.io/s/hardcore-sun-yyx0g?file=/src/DropdownView.jsx

Answer №2

If you prefer not to use styles from the parent div, you can apply them directly to the elements like this: https://codesandbox.io/s/eloquent-lamport-3spzr?file=/src/App.js

However, if you do want to utilize styles from the parent, you can pass them using a specific name as shown below:

<Dropdown
    inputName="viola"
    list={[
        { yard_id: "1", yard_name: "Yard 1" },
        { yard_id: "2", yard_name: "Yard 2" }
    ]}
    // this style is for className="select-box-current"
    selectBoxCurrentStyle={{ border: "1px solid #D4D4D4" }}
    // this style is for className="select-box-list"
    selectBoxListStyle={{
        opacity: 1,
        display: "inherit",
        animationName: "none",
        cursor: "pointer"
    }}
/>

For more information, visit this link: https://codesandbox.io/s/damp-rain-cyhxb?file=/src/App.js:133-643

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

Setting the timezone for the DateTimeInput component in React-Admin is a crucial step for

My API returns datetime in the format '2021-12-31T16:00:00.000Z' I need to use DateTimeInput and consistently show it in UTC+8 timezone. After the user submits the form, it should convert back to the original format '2021-12-31T16:00:00.000 ...

Applying CDNJS CSS or external CSS to Nodemailer HTML templates with Jade and Express: A Guide

I am attempting to send emails using node mailer. I have a jade template with HTML markup in an external file, which is compiled and rendered correctly. However, the styles inserted through maxcdn or cdnjs are not being applied. In this situation, how can ...

Using a JavaScript if statement to check the height of a specific HTML element

I have been struggling to figure out how to insert an if-else statement in JavaScript that references data about an HTML element. My objective is to create an "onclick" function that enlarges an image with a 200ms delay and another function that returns th ...

Ways to bypass mongoose schema validation while making an update request in the API

In my model, one of the fields is specified as providerID: { type: Number, required: true, unique: true }. The providerID is a unique number that is assigned when inserting provider details for the first time. There are situations where I need to update ...

When working with React, I often encounter situations where I receive very similar Unix timestamps from the `<TextField type="date">` component

I am facing an issue with setting the start date and due date using two Textfield components. Check out the code snippet below: const startDateChange = (e) => { setStartDate(Math.floor(new Date().getTime(e.target.value) / 1000)); console.log(startD ...

Transitioning the width in CSS without using the "auto"

Currently, I am experiencing a problem with my CSS animation that is leaping directly from the start to finish. It appears to be connected to a similar issue addressed in this thread. My inquiry is: Is there a way to create a smooth transition in width f ...

I am currently working on implementing data filtering in my project. The data is being passed from a child component to a parent component as checkboxes. Can anyone guide me on how to achieve this filtering process

Below is the code I have written to filter data based on priorities (low, medium, high). The variable priorityArr is used to store the filtered data obtained from "this.data". The following code snippet is from the parent component, where "prio" is the v ...

What is the best way to customize the appearance of a toggle switch using useStyles in Material UI, rather than withStyles?

I need help with customizing the styling of an input form switch in Material UI. I want the track and button to turn red when the switch is on, similar to this example. I have tried using the withStyles method following examples on the Material UI website, ...

What's the best way to position the <li> element beneath the hamburger icon?

Is there a way to place the list element 'Home' below the hamburger icon and logo in Bootstrap 4 in mobile mode? I attempted to display the logo as style="display: block" with no success. <div class="container"> <nav class="navbar nav ...

Make sure to include additional details, such as copyright information and a link to read more, when copying text. It is also important to maintain the

When attempting to include a read more link in my copied text, I am encountering an issue where the line breaks and formatting are being neglected: <script type='text/javascript'> function addLink() { var body_element = document.getEl ...

Expo - The package name 'com.xxx.native.xxx' specified in AndroidManifest.xml is invalid for use in Java, as 'native' is a reserved Java keyword

For as long as I can remember, I've been using the pattern 'com.mycompanyname.native.appname' to name the bundle Ids for my apps. This approach has served me well over the years and I've created numerous apps with the keyword "native" i ...

Utilizing external objects within the data() function of Vue: A comprehensive guide

When it comes to defining data in a Vue component, the typical approach is to use the data function as shown below: data() { return { a: 0 } } But I have a question: instead of defining the data object after return, is it possible to defin ...

What sets Fetch apart from ajax and XMLHttpRequest that makes it impressively faster?

Over the past few days, I have been working on optimizing a client table for a project. The table contains over 10k clients, and as a result, it was taking a long time to load. The front-end team had implemented pagination, filters, and reordering, which ...

Jquery loader for loading html and php files

My html and php pages contain a significant amount of data which causes them to take a few extra seconds to load from the server. I was wondering if there is a way to implement a "loader animation" for these pages using jquery. The idea is for the loader a ...

Solution for repairing the display location button on Android within a React Native Map

I am facing an issue with the Location Button in my React Native Maps app. When the app is opened for the first time and the map is rendered, the button disappears. However, if I close the app but leave it running in the background, upon reopening the app, ...

How can I use JavaScript and HTML to print a canvas that is not within the print boundaries?

As someone who is new to javascript, I recently created a canvas function that allows me to successfully print. However, I am encountering an issue with printing large canvas areas. When I navigate to the further regions of the canvas and try to print, i ...

Utilizing JavaScript with an ASP.NET dropdownlist: A step-by-step guide

Although I'm not currently using ajax.net, I am open to exploring it as a potential solution. Currently, I have an auto-complete control on my screen that is populating an asp.net dropdownlist with values through JavaScript (jQuery). In order to make ...

Limiting the use of JavaScript widgets to specific domains

In the process of developing a webservice that offers Javascript widgets and Ajax calls limited to specific domains, I have explored various options. However, my research has led me to consider using a combination of HTTP-Referer and API Keys for access ...

Conflicting dependencies between MUI and React have caused an issue

Attempting to deploy a React project using MUI icons and components, I encountered errors while deploying on Vercel. The errors can be viewed here. Here is a snippet from my package.lock file: { "name": "course", "version": "0.1.0", "private": true, ...

How to extract the HTML content from specific text nodes using Javascript

I have a piece of HTML that looks like this: <div id="editable_phrase"> <span data-id="42">My</span> <span data-id="43">very</span> <span data-id="1">first</span> <span data-id="21">phrase< ...