Apply a style to the div element that contains a TextInput component

As a beginner in the world of React and Material UI, I am currently working with Material UI version "1.0.0-beta.17", React 15.6.2, styled-components 2.0.0, and styled-components-breakpoint 1.0.1.

Within a div element, I have two TextInput fields.

const mycomponent = ({props}) => {
  <div>

    <SomeComponent />
    <div>
       <TextInput id="testId1" />
       <TextInput id="testId2" />
    </div>

  </div>
}

Upon rendering, an additional parent div is added to each input field like this:

<div>
    <div class="field--testId1">
       <div class="FormItem__ElementWrapper-s14tem39-3 bgVlIQ">
           <input id="testId1">
       </div>
    </div>

    <div class="field--testId2">
       <div class="FormItem__ElementWrapper-s14tem39-3 bgVlIQ">
           <input id="testId2">
       </div>
    </div>
</div>

I am now wondering how I can target these divs to apply styles using the class names field--testId1 and field--testId2. These class names are generated by default in Material UI.

.field--testId1{
  width: "48%",
  float: "left"
}
.field--testId2{
  width: "48%",
  float: "left"
}

Any assistance on how to achieve this in React and Material UI would be greatly appreciated.

Answer №1

If you want to replace an existing class, one way to do it is by using a styled-component wrapper instead of the normal wrapping div and then override the child classes:

 const FormElementWrapper = styled.div`
     .element--testId2 {
          // your unique styling here
     }
 `
<FormElementWrapper>
   <FormElement id="testId1" />
   <FormElement id="testId2" />
</FormElementWrapper>

Answer №2

If you're looking to specifically target a div element containing an input, here are some steps you can take:

  • Assign a class, such as wrapper, to the parent div
  • Use the > CSS selector to target the closest div

.wrapper > div {
  border: 1px solid red;
  width: 48%;
  float: left;
  margin-left: 1%;
}

input {
  width: 100%;
  box-sizing: border-box;
}
<div class="wrapper">
    <div class="field--testId1">
       <div class="FormItem__ElementWrapper-s14tem39-3 bgVlIQ">
           <input id="testId1">
       </div>
    </div>

    <div class="field--testId2">
       <div class="FormItem__ElementWrapper-s14tem39-3 bgVlIQ">
           <input id="testId2">
       </div>
    </div>
</div>

Answer №3

By assigning a class directly to your textfield element, you have the ability to incorporate your own unique styling.

  <input type="text" class="custom-style" id="inputField1" />

Answer №4

In order to enhance your component's styles, it is recommended to utilize @material-ui/styles. A helpful example that aligns with your scenario can be found here: . Below is a demonstration:

To customize the styles of your Text Fields effectively, you should integrate @material-ui/styles as illustrated below:

import React from 'react';
import { makeStyles, TextField } from '@material-ui/core';

const useStyles = makeStyles({
  textField: {
    border: 0,
    borderRadius: 3,
    padding: '0px 30px',
    // Additional styles can be added here...
  },
});

export default function MyComponent() {
    const classes = useStyles();
    return (
        <div>
            <TextField 
                size="large"
                variant="outlined"
                label="A text field title"
                className={classes.textField}
            />
        </div>
    );
}

For more detailed information, refer to the documentation available at this link: @material-ui.com/styles

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

How can you use React.js to only display "Loading..." on the page while the full name is included in the URL?

I've hit a roadblock while trying to solve this issue. Here's the situation: On the page where I need to display certain information, I intended to showcase the full name of the individual from a previous form submission. However, instead of seei ...

React: Render function did not return any content. This typically indicates that a return statement is missing

Can anyone help me troubleshoot this error? Error: CountryList(...): No render was found. This typically indicates a missing return statement. Alternatively, to display nothing, return null index.js import React from 'react'; import ReactDOM f ...

Creating a Class in REACT

Hello fellow coding enthusiasts, I am facing a minor issue. I am relatively new to REACT and Typescript, which is why I need some assistance with the following code implementation. I require the code to be transformed into a class for reusability purposes ...

Utilizing jQuery to implement a CSS style with a fading effect, such as FadeIn()

I have a jQuery script that applies a CSS style to an HTML table row when the user clicks on a row link: $(this).closest('tr').css("background-color", "silver"); Is there a way to soften this color change effect, such as by gradually fading in ...

The image fails to appear while creating a PDF in AngularJS using pdfmake

I recently started using a fantastic pdf printing library called pdfmake in my angularjs SPA to generate PDF files. Everything was going smoothly until I tried to include images in the PDF. Strangely, when I added images, nothing happened - no errors, no e ...

Trouble with Bootstrap 5 Dropdown Menu failing to drop down

I am attempting to utilize a dropdown menu on my Wordpress site with Bootstrap, but it is not working as expected. If I manually add the class "show" to my dropdown-menu div, the menu displays, but the button does not function. These are the scripts being ...

What steps can I take to correct my code so that it only shows a single table?

I'm facing an issue while trying to display my dynamic JSON data. It's rendering a table for each result instead of all results in the same table. My array data is coming from the backend API. const arr = [ { "Demo": [ ...

Updating styled-components variables based on media queries - A step-by-step guide

My current theme setup looks like this: const theme = {color: red}; Within my components, I am utilizing this variable as follows: const Button = styled.button` color: ${props => props.theme.color}; `; I am now faced with the challenge of changin ...

A guide on sorting an array based on elements from a different array

We are currently in the process of developing an application using Vue and Vuex. Our goal is to display a list of titles for venues that a user is following, based on an array of venue IDs. For instance: venues: [ {venue:1, title: Shoreline} {venue:2, ti ...

Toggle the status of active to inactive instantaneously with the click of a

Incorporating DataTables with ajax using PHP CodeIgniter Framework has presented me with a challenge. I am struggling to toggle between Active and Inactive buttons seamlessly. My desired outcome: When the Active button is clicked, it should transition ...

Utilize JavaScript to substitute font family with a designated class name

After discovering a code snippet that can change font family based on ID, I am interested in implementing it on my website but with a twist - using classes instead of IDs. <!DOCTYPE html> <html> <body> <div class="myP">This is a ...

Display the input in the text box before making a selection from the dropdown menu

Latest Technologies: $(document).ready(function(){ $('#userID').change(function(){ $('#username').val($('#userID option:selected').data('username')); }); }); Coding in HTML: <select class="form- ...

Having trouble retrieving values from JSON properties

My mind is boggled by this issue, and I have a feeling it's just a simple oversight! I'm dealing with a service that sends back a JSON object: [{"accountId":"0000004000006195","title":null,"firstName":"JOE","middleName":"BLOG","lastName":"BLOGG ...

align all items centrally and customize Excel columns based on the length of the data

Is there a way to dynamically adjust the column width based on the length of data in an Excel report using PHPexcel? Additionally, how can I center all the data in the Excel sheet? Here is the current code snippet: <?php if (!isset($_POST['send&a ...

Exception in posting strings or JSON with react.js

Whenever a user clicks on the Signup button, the process I follow to create an account is as follows: Firstly, a new User entry is created in the database. createUser = () =>{ var xhr = new XMLHttpRequest(); xhr.open('POST', 'http:// ...

Is there a way to conceal the parameters in the PHP GET method?

How to convert PHP GET method URL to a cleaner format? example.com/example.php?name=45 to example.com/example.php/45 Is it possible to achieve this using the .htaccess file? ...

react-video-recorder` facing challenges with loading

I recently integrated react-video-recorder into my application. After checking out the demos on Stackblitz and Storybook hosted on Vercel, I was impressed with how well it worked in my browsers. However, when I added it to my codebase, the component would ...

Incomplete header data in Angular $resource GET request

Currently, I am working with Ionic 1.3 and Angular 1.5. My goal is to retrieve some header properties from my response. The code snippet I am using looks something like this: factory('Service', function($resource, API_SETTINGS, JsonData) { re ...

Console shows successful jQuery ajax request, but the callback function is not being executed

I've been working on a jQuery POST request that's been giving me some trouble. Here is a snippet of the code I'm using: $.ajax("/myurl",{ data:{ ... }, mimeType:"application/json", dataType:"application/json", me ...

Is there a reason why the JSX select element does not automatically select the option (implementing 'selected')? I'm unsure if I am overlooking something

In my HTML, I have a snippet of code that defines a custom <SelectField> component using a <select> tag like this: export default function SelectField(props) { /* PARAMETERS: - fieldname (String) - fieldID (String) - options (A ...