What is the best way to specifically target and style a component with CSS in a React application?

I'm facing a small issue with the React modals from Bootstrap in my application.

In index.html, I include the following:

<link rel="stylesheet" href="/assets/css/bootstrap.min.css">
<link rel="stylesheet" href="/assets/css/bootstrap-theme.min.css">

However, the CSS is being applied to everything in my app which is causing a style break. Customizing all the Bootstrap classes in my component is not feasible, so I need to find a way to apply these styles only to my modal component.

Here is the code for my modal:

import React from 'react';
import Modal from 'react-bootstrap/Modal';
import Button from 'react-bootstrap/Button';

import { useTranslation } from 'react-i18next';
import Form from 'components/forms/Form';
import FileInput from 'components/forms/FileInput';

function PicturesUploadModal (props) {
  const { t } = useTranslation('common');

  return (
    <Modal show={props.modalOpen} onHide={props.handleClose}>
      <Modal.Header closeButton>
        <Modal.Title>{ t('addPictures') }</Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <p>{ t('numberPics') } {30 - props.images.length}</p>
        <input type="file" onChange={props.handleChange} multiple />
        {(props.error === true) && <p className="alert alert-danger">{t('filesErrors')}</p>}
      </Modal.Body>
      <Modal.Footer>
        <Button variant="secondary" onClick={props.handleClose}>
          { t('close') }
        </Button>
        <Button variant="primary" onClick={props.handleSubmit}>
          { t('sendSave')}
        </Button>
      </Modal.Footer>
    </Modal>

  );
}

export default PicturesUploadModal;

Could someone please suggest how I can ensure that the previously imported styles are ONLY applied to the Modal component?

Thank you!

Answer №1

For an optimal solution in implementing modals, I highly recommend utilizing the react-modal library. This will effectively resolve any potential conflicts with Bootstrap and ensure your styles remain unaffected. To access the npm package, you can visit: https://www.npmjs.com/package/react-modal

Answer №2

Experiment with including a new class and styling it with CSS

<Modal show={props.modalOpen} onHide={props.handleClose} className: 'your-class'>

Answer №3

import React from 'react';
import Modal from 'react-bootstrap/Modal';
import Button from 'react-bootstrap/Button';
import styled from 'styled-components'; // Added this for styling
import { useTranslation } from 'react-i18next';
import Form from 'components/forms/Form';
import FileInput from 'components/forms/FileInput';

const Styles = styled.div`
    .yourclassName{
        margin: 2px;
     }
`

function PicturesUploadModal (props) {
  const { t } = useTranslation('common');

  return (
   <Styles>
    <div className="yourclassName">Modal</div>
    <Modal show={props.modalOpen} onHide={props.handleClose}>
      <Modal.Header closeButton>
        <Modal.Title>{ t('addPictures') }</Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <p>{ t('numberPics') } {30 - props.images.length}</p>
        <input type="file" onChange={props.handleChange} multiple />
        {(props.error === true) && <p className="alert alert-danger">{t('filesErrors')}</p>}
      </Modal.Body>
      <Modal.Footer>
        <Button variant="secondary" onClick={props.handleClose}>
          { t('close') }
        </Button>
        <Button variant="primary" onClick={props.handleSubmit}>
          { t('sendSave')}
        </Button>
      </Modal.Footer>
    </Modal>
</Styles>
  );
}

export default PicturesUploadModal;

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

Vuejs - Expanding Panels

Trying to implement an accordion using Vue.js has been a bit challenging for me. While I came across some examples online, my requirements are slightly different. In order to maintain SEO compatibility, I need to use "is" and "inline-template", which make ...

An issue occurred while trying to use a function that has a return type of NextPage

After successfully implementing the code below: const HomePage: NextPage = () => ( <div> <div>HomePage</div> </div> ); I wanted to adhere to Airbnb's style guide, which required using a named function. This led me t ...

Troubles with basic jQuery hide and show functionalities

Hey there! I've been working on a project for the past couple of days and I'm having trouble with creating a slider effect using jQuery hide and show. It's strange because my code works perfectly fine with jquery-1.6.2.min.js, but when I swi ...

Prevent ng-repeat from rendering the contents of my div

Currently, I am in the process of modifying a website for which I need AngularJS. I am trying to use the ng-repeat command to display some documentation on the site. However, whenever I add the ng-repeat within a div, it seems to "destroy" the layout and I ...

The Electron/React/Typescript module is missing: Error: Unable to locate 'fs' in the /node_modules/electron directory

Within my Electron application, I have a file named App.ts. It contains the following code snippet: import { ipcRenderer } from 'electron'; // remaining code However, during the app development process, I encountered this error message: Error: ...

The `npm start` command is malfunctioning following modifications to the PATH system environment variable

Upon attempting to launch my react application using npm start, an error is encountered: events.js:377 throw er; // Unhandled 'error' event ^ Error: spawn powershell ENOENT at Process.ChildProcess._handle.onexit (internal/child_p ...

The response from the Ajax request in jQuery did not contain any content to download

I have a PHP script that generates PDF output successfully when accessed directly. Now, I want to fetch this PDF file using AJAX. In pure JavaScript, the following code snippet works well: var req = new XMLHttpRequest(); req.open("POST", "./api/pd ...

The infinite loop issue arises when the useEffect is utilizing the useNavigate hook

As I integrate the useNavigate hook within React to guide users to a specific page post-login, an unexpected infinite loop arises. Most sources online recommend utilizing the useNavigate hook inside a useEffect block; however, this method triggers a Warnin ...

The server side props in Next.js are not being loaded promptly

I am currently utilizing Supabase and facing an issue with loading the user session on the server side. When a page is refreshed, it recognizes that there is a user but not on the initial load (such as when coming from a magic link). How can I ensure that ...

"Standard" approach for a Date instance

During my time in the Node REPL environment, the following output was displayed: > console.log(new Date()) 2023-08-15T09:21:45.762Z undefined > console.log(new Date().toString()) Sun Aug 15 2023 09:21:50 GMT+0000 (Coordinated Universal Time) undefine ...

The header is displaying with the heading and image out of alignment

Take a look at my code header img{ width:10%; vertical-align: middle; } header h1{ text-align: right; display:inline; position: absolute; } header { width : 100%; height: 1% ; background: red; } <!DOCTYPE html> <html> <head> <m ...

Struggling with parameter passing issues and preparing code for seamless integration with MYSQL database

I've been dedicating the past four days to a project that I've crafted entirely by hand to test my JavaScript skills as I progress through Codecademy courses. The goal is to develop a browser-based checklist program, and so far, I've success ...

The debate between ensuring input validity and making fields mandatory on multi-page forms

I am currently working on a multi-page form and using jQuery Validate to validate it. The user has four options: next, prev, save, submit. Save, next, and prev all save the current page within the form; whereas submit is similar to save, but triggers addi ...

Having trouble using jQuery to target the element "(this)"?

Currently, I am delving into jQuery and have stumbled upon a section that perplexes me. Due to my lack of familiarity with the terminology, conducting an effective Google search has proven difficult. Therefore, I decided to craft this question to elucidate ...

Tips for preventing menu flickering caused by overflow during CSS animations

I recently created a vertical menu with an interesting underline effect that appears when hovering over the menu items. Even though the snippet initially failed to execute, I discovered this cool hover effect (taken from here) which I wanted to implement: ...

An exploration of toggling states within an array using ReactJS and hooks

Hello there, I need some assistance with a problem I'm facing. Here's the scenario: I have a checkbox and an array of objects retrieved from an API request: const ownRequest= [ {status: "pending", type: "aaa"}, {status: "pending", type: "bbb"} ...

React Project Initialization Error: Module Not Located | webpack-dev-server Issue

Lately, I've been consistently facing a 'Module not found' error every time I execute npm start or yarn start on my local machine. Interestingly, this error only pops up when I create a new project locally; projects cloned from GitHub work w ...

Using Redux to retrieve external key values in order to associate them with card components

After implementing include functionality for foreign keys in my backend API controller, the values are now being fetched into my Redux store, where I intend to use them. However, I am facing challenges in accessing these values when attempting to map them ...

Code in jQuery or JavaScript to retrieve precise node information for the currently selected form field, text, or image on a webpage

Looking to retrieve specific information about the item that has been clicked on a web page using jquery. The clickable item could be a form element (like a checkbox, text box, or text area) or a section of text within a paragraph, div, list, or image... ...

Necessary workaround needed for HTML time limit

Our HTML page has been designed to automatically timeout after 10 minutes of inactivity. This functionality is achieved through the following code: function CheckExpire() { $.ajax({ type:'GET', url:self.location.pathname+"?ch ...