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

Mastering the art of completing a form using AJAX

I'm working on a checkbox that triggers AJAX to create a new log. It populates the necessary information and automatically clicks the "create" button. However, I'm facing an issue where the hour value is not changing. Any help on what I might be ...

Issue with jQuery .hover() not functioning as expected

The issue I'm encountering is just as described in the title. The code functions correctly on all divs except for one! $(".complete-wrapper-1").hide(); var panelHH = $(".file-select-wrapper").innerHeight; $(".files-button").hover(function(){ $(" ...

Instead of displaying a regular text box, the output unexpectedly shows "Printing [object HTML

There are some HTML and JavaScript files that I have. I've written some functions in my JavaScript file to save the values of different input fields. However, when I try to print the description, it just displays [object HTMLInputElement]. This mak ...

Retrieving attributes by their names using dots in HTML

Currently working on an Angular 2 website, I am faced with the challenge of displaying data from an object retrieved from the backend. The structure of the object is as follows: { version: 3.0.0, gauges:{ jvm.memory.total.used:{ value: 3546546 }}} The is ...

Encountering a syntax error when attempting to incorporate a ternary expression within a string interpolation

<The image source is determined by whether expand[0] is true or false, with the path being '../assets/expand.png' if true and '../assets/expandDown.png' if false.> The user is encountering a syntax error. What could be causing it ...

Is there a way for me to retrieve SCSS color variables within the javascript of a Vue template?

I have a unique challenge in my application involving a component called Notification. To bring notifications to other components, I utilize the mixin method toast('message to display', 'color-variable'). My goal is to set the backgroun ...

implementing a delay after hovering over a CSS hover effect before activating it

I'm trying to achieve a specific effect using JavaScript or jQuery, but I'm struggling to figure it out. I have created a simple CSS box with a hover effect that changes the color. What I want is for the hover effect to persist for a set amount o ...

Can the name of a React Component that is nested and inner be retrieved by invoking a function from one of its props?

I am currently working with this particular component: class DashboardPage extends Component { constructor(props) { super(props); this.state = { loading: true, shownPage: ActiveDeals, error: false, errorDetails: null, ...

VueJS: interactive input field with dynamic value binding using v-model

I am facing an issue with VueJS regarding setting the value of an input radio along with v-model. I am confused as to why I am unable to dynamically set a value to an input and use a model to retrieve the user's selection. Here is a clearer represent ...

Is there logic in developing a web application using a combination of a NestJS backend and Next.js frontend, along with authentication features?

Currently, I am embarking on the journey of developing a web application using React and Next.js. With my previous experience in backend development using NestJS, I decided to integrate it into this project as well. However, I am unsure if separating the f ...

Retrieve the output of a JavaScript function and submit it as extra form data

I am working on a JavaScript function that looks like this: <script type="text/javascript"> function doSomething() { var s = 'some data' return s; } </script> and @using (Html.BeginForm(new { data_to_send = ...

Verify whether an HTML element lies within another HTML element

Consider this example: <div id="President"> <div id="Congressman"> <div id="Senator"> <div id="Major"></div> </div> </div> </div> Is there a simple way in JavaScript or jQuery to determine ...

Angular repeatedly executes the controller multiple times

I have been working on developing a chat web app that functions as a single page application. To achieve this, I have integrated Angular Router for routing purposes and socket-io for message transmission from client to server. The navigation between routes ...

javascript the unseen element becomes visible upon page loading

my website has the following HTML snippet: function getURLParameters() { var parameters = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { parameters[key] = value; }); return param ...

Preventing Duplicate Random Numbers in Vue 3 and JavaScript: A Guide

I've been working on creating a function that can iterate through an array of objects with names and IDs, randomize the array, and then return one filtered item to slots.value. The current spin function successfully loops through the randomized object ...

Filtering objects by their properties or attributes in AngularJS can be achieved by using forEach, but encountering an error stating "forEach is

In my AngularJS application, I have a page that displays multiple widgets. One widget shows a table with details about a monitored system. Currently, the table has two columns: 'Type' and 'Data', displaying information and values respec ...

Maintain the original order of rows in the table while shuffling the columns they appear in randomly

I need help with my table setup. The left column contains words in English, while the right column has the same words translated into Korean. Is there a way to keep the rows intact while randomizing the order of the columns? Here's an example: <ta ...

How can we prevent the modal from extending beyond the boundaries of the phone screen when zoomed in

I am currently developing a web application that features a large content page, specifically a map which should display detailed information upon zooming in similar to Google Maps. The interactive elements on my map are clickable, triggering a modal popup ...

Is the form validation failing to update after an item is removed from the model? Possible bug detected?

Lately, I've been exploring AngularJS and encountered an interesting bug. Let me start by sharing some functional code: View: <body ng-controller="MainCtrl"> <form name="form"> <div ng-repeat="phone in phoneNumbers"> ...

Using Selenium 2 to dynamically insert CSS styles into the currently visible webpage

I experimented with using jQuery on a webpage that has already been modified by jQuery in order to add custom CSS code: jQuery('head').append('<style type=\"text/css\">body { background: #000; }</style>'); When I ...