Enhancing the Look of Custom HTML Tags with React JSS Styling

I have incorporated material-ui into my project, here is an example of the code I am using:

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

const useStyles = makeStyles((theme) => ({
  root: {
    '& > *': {
      margin: theme.spacing(1),
    },
  },
}));

export default function ContainedButtons() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <Button variant="contained">Default</Button>
      <Button variant="contained" color="primary">
        Primary
      </Button>
      <Button variant="contained" color="secondary">
        Secondary
      </Button>
      <Button variant="contained" disabled>
        Disabled
      </Button>
      <Button variant="contained" color="primary" href="#contained-buttons">
        Link
      </Button>
    </div>
  );
}

This is my first experience with jss. As I experiment with & > *, attempting to grasp its functionality, it appears to be a CSS selector. However, after reviewing the documentation available here and here, I am encountering some confusion regarding the following:

  1. While * and > are familiar CSS selectors, can you explain the meaning behind & in this context?

  2. If I aim to restrict the CSS selector application solely to buttons, should I utilize & > button or & > Button? Both seem to work, but considering that the final output presented to the browser is button, would it be preferred to opt for & > button?

Answer №1

Topic 1: React libraries like JSS and styled-components bring SCSS (Sass) functionalities to CSS-in-JS for enhanced CSS features.

The use of & in CSS is not common because it is a feature specific to SCSS (Sass). Sass extends regular CSS with additional capabilities:

  • Nesting can be used when styling components or HTML elements.
  • & acts as the parent selector, referencing the nested HTML element.

In the provided example, & refers to root as it is directly nested within it. & > * applies styles to all direct descendant elements (*) of root (&).

root: {
  '& > *': {
    margin: theme.spacing(1),
  }
}

Illustration: Utilizing & can simplify tasks, such as adding a hover state to a button.

In standard CSS, you would do this:

button {
  background-color: tomato;
}

button:hover {
  opacity: 0.5;
}

With SCSS, nesting and the parent selector (&) enable a more concise approach:

button {
  background-color: tomato;
  &:hover {
  opacity: 0.5;
  }
}
  1. Source: https://cssinjs.org/from-sass-to-cssinjs
  2. Source: https://sass-lang.com/documentation/style-rules/declarations#nesting
  3. Source: https://sass-lang.com/documentation/style-rules/parent-selector
  4. Source: https://styled-components.com/docs/faqs#can-i-nest-rules

Topic 2: ReactJS components begin with uppercase letters, while HTML Elements start with lowercase letters. For instance, Button represents a React component, whereas button denotes an HTML element.

You could construct a Button component comprising a button with an img and a p included.

& > Button will target all Button React components directly descending from & (The value of & varies depending on context), while & > will select all button HTML elements that are direct descendants of &.

Scenario: Consider a scenario where a div contains a Button React Component (with a button HTML element) and a ToggleButton React Component (also featuring a button HTML element):

  • Using & > Button selects only the button HTML element inside the Button that is a direct child of the div (&).
  • Applying & > button targets the button HTML elements in both Button and ToggleButton that are direct children of the div (&).

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

Using React with Redux, implement a router saga that is integrated with material-ui tabs to reflect the

As a newcomer to react, I am currently utilizing react-boilerplate along with material-ui In my project, I have tabs structured like this: https://i.sstatic.net/JiqGO.png My goal is to implement functionality where changing the current tab will also upda ...

How to modify the Material-UI TextField color when it is not in focus

I am currently using the TextField below and it is working correctly. However, I would like to change the color of the label when it is not in focus, as it currently remains black. Can someone provide guidance on how I can achieve this? const useStyles = ...

Tips for Creating an Upward-Dropping Dropdown Menu in HTML/JavaScript When Space is Limited on the Page

Hello, I am currently seeking a solution to adjust my dropdown menu so that it appears above instead of below when the page doesn't have enough space to display it fully. My tools for this project include HTML, Javascript, CSS, and JQuery exclusively. ...

Apply specific classes to elements when they become visible on the screen

I am currently utilizing a script that adds a class to a div once it enters the viewport. The issue I am facing is that this script applies to multiple divs, causing the class to be added to all of them once the first one is visible. Is there a more effici ...

What causes the appearance of an HTTP header error and how can we identify the bug?

I tried to convert XML to JSON using two files which are included here. However, I keep encountering an error. Despite searching on SO for solutions, I haven't been able to find the answers. main.js /** SET ENGINE TO PUG */ app.set("views", ...

unable to perform a specific binary operation

Is there an efficient method to achieve the following using binary operations? First byte : 1001 1110 Second byte : 0001 0011 Desired outcome : 1000 1100 I am looking to reset all bits in the first byte that correspond to bit values of 1 in the secon ...

Stop or abort any pending API requests in Restangular

I am currently working with an API service: var SearchSuggestionApi = function (Restangular) { return { getSuggestion: function (keyword) { return Restangular.one('search').customGET(null, {keyword:keyword}); } }; }; SearchS ...

Can you explain the different types of dynamic page props available in a Next.js application?

Is there a specific type available in Next.js 14 that I can use to replace the "any" type in the TypeScript code snippet below, for my dynamic route? export default async function DetailProduct({ params }: any) { const { imageAddress, title, price } = ...

Using Material UI with React and TypeScript

I need some assistance with organizing my menus correctly in React using TypeScript. Currently, they are displaying on top of each other instead of within their respective category menus. I have been struggling to find a solution and would appreciate any h ...

Mongoose: strange outcomes observed when trying to delete the final element from an array

Update: I made a change in my approach by filtering the array directly and saving it instead of using updateOne and $pull. Surprisingly, this fixed the issue of html elements getting removed. However, the same problem persists when deleting the last item i ...

Starting a Fresh Chapter Upon Successful Form Submission with PHP

https://i.sstatic.net/ZEHSL.png I am utilizing PHP to control form elements. If the elements are invalid, I display an error message below them. My issue arises when all form elements are valid, but the page does not redirect to the desired destination pa ...

triggering a function from a child component in React

I am facing a challenge in calling a function from the parent component that is stored in a child component. I understand how to do it from child to parent using props, but unsure about how to achieve it from parent to child. In the example below, you can ...

What could be causing JavaScript Ajax calls to fail over SSL specifically on IOS devices, with the exception of IOS

I am encountering an issue with a mobile application I have developed. It makes an ajax xmlHttpRequest request over SSL to another application on the same domain in order to authenticate a user. Strangely, this call fails with response code zero on IOS dev ...

Stopping the setTimeout function triggered by a click event in a Reactjs application

I'm a beginner with Reactjs and I ran into a dilemma while using setTimeOut. I couldn't figure out whether to use clearTimeOut or stopPropagation() to stop it. Here's my code: render: function() { return ( < div className = "colorCl ...

Ways to keep the position of an expanded collapsible table from Material UI intact

I found a collapsible table code snippet on this website: https://mui.com/material-ui/react-table/#collapsible-table However, there seems to be an issue where when I expand a row, the table "grows up" as it increases in size. This behavior is not ideal. I ...

Issue with PrimeNG Calendar not updating date value within modal

While using the PrimeNG Calendar control, I encountered an issue. Even though I am able to select and store dates, when I try to fetch dates from a database and update the Modal, I receive the following error message: https://i.sstatic.net/LWSUF.png <p ...

Displaying iterative content using Vue.js from an array of items

Looking to style questions and answers differently when rendering them. The data structure is as follows: dialogTut:{ mainTab:{ q:"data with 42 people?", a:"hehe", q:"Are awesome people?", a:"sometimes", ...

While typing, React-hook-form is removing the input field when the mode property is enabled

Currently, I am implementing a basic form using react-hook-form version 7 along with Material UI. However, I have encountered an unusual behavior when configuring the mode in useForm({mode: ".."}). Below is a snippet of my code: import { yupResol ...

What is the process for displaying an open file dialog box when a user clicks on an icon image?

Is there a way to display the open file dialog when a user clicks on the icon image? I attempted to use the input "" tag, but it automatically adds a button. Is there a method to make this button invisible? ...

Utilizing angularjs to send an image along with additional form fields to a spring rest service

I am looking to create a webpage that allows users to upload an image along with other form fields using AngularJS and Spring REST service. Below is the example of HTML code: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3 ...