Exploring the process of passing parameters in Material-UI React styled components

Recently, I developed a new component

const CategoryDialog = (props) => {
  const classes = useStyles();

  console.log(props);

  return (
    <div>
      <Dialog
        fullScreen
        open={props.dilaogOpenProp}
        TransitionComponent={Transition}
      >
        <AppBar className={classes.AppBar} sx={{ position: "relative" }}>
          <Toolbar>
            {/* <IconButton
              edge="start"
              color="inherit"
              aria-label="close"
              onClick={props.onDialogClose}
            >
              <CloseIcon />
            </IconButton> */}
            <Typography
              
              sx={{ ml: 2, flex: 1 }}
              variant="h2"
              component="div"
            >
              <span className={classes.Text}>{props.showCategoryMarbleOnDialog?.qualityName}</span>
              
            </Typography>
            <Button
              autoFocus
              color="error"
              variant='contained'
              onClick={props.onDialogClose}
            >
              Back
            </Button>
          </Toolbar>
        </AppBar>
        <List></List>
      </Dialog>
    </div>
  );
};

export default CategoryDialog;

The above code showcases the styles for this particular component.

   import { makeStyles,createTheme } from '@material-ui/styles';

export default makeStyles(theme => ({
    AppBar:{
        background:'url("https://4.imimg.com/data4/LW/DQ/MY-10354786/artificial-quartz-500x500.jpg")',
        objectFit: 'cover',
        color:'black',
        height:'300px'
    },
    Text:{
        backgroundColor:'rgba(0,0,0,0.4)',
        padding:'10px',
        color:'white',
        position: 'absolute',
        top:'10px',
        left:'10px'
    },
    Button:{
        backgroundColor:'rgba(0,0,0,0.1)',
        padding:'10px'
    },    
}));

I am considering replacing the static image link in the CSS of AppBar with a dynamically passed prop image. For example:

AppBar:{
            background:'url(`$(image)`)',
            objectFit: 'cover',
            color:'black',
            height:'300px'

Answer №1

Here is a solution on how to effectively use both props and themes in Material UI: To achieve this, you simply need to pass an image as props to the useStyles function.

import backgroundImage from "images/404/404-error.svg"; 

       const useStyles = (image)=> makeStyles( theme => ({
        AppBar: {
            background: `url(${image})`,
        }
    }));
    
    export default function ExampleComponent({ children, ...props }){
      const classes = useStyles(backgroundImage)();
        return (
             <AppBar
                    
                    className={clsx(classes.appBar, {
                        [classes.appBarShift]: open,
                    })}
                />
        );
    }

I have tested this solution and it works flawlessly!

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

Issue with ajax form: success function is not functioning as intended

For my form submission, I am utilizing ajaxForm(options) to run some functions before submitting the form. Here is an example of the options that I have configured: var options = { target : '#output1', success : ...

What is the correct method for closing a style element in Nextjs JSX?

Having trouble adding some unique styling to a jsx component. The code snippet below is throwing an error when compiled. import Card from "./card"; export default function CardRow(){ return( <> <div> <Card> ...

Learn the best practices for incorporating jQuery and other JavaScript libraries in your Angular2 projects

Is it possible to integrate a demo showcasing Bootstrap carousel with CSS3 animations in Angular2 using HTML, CSS, and JS? I have created my own implementation in Plunker with Angular2, but I am facing issues with the animated inner content of the carousel ...

Spring load without CSS

Upon successful login, I am redirected to my main site using the following controller: //Login Success @GetMapping("/login-success") public ModelAndView loginSuccess() { return new ModelAndView("/cont/home.html"); } The URL for this redirection i ...

Creating a dynamic list in HTML by populating it with randomly selected words using JavaScript

Check out my awesome code snippet function wordSelect() { var words = ["Vancouver", "Whistler", "Surrey", "Victoria", "Kelowna"]; //List of randomly-selected words from above var selectedWords = []; for(let i = 0; i &l ...

New features in Next.js 13 include an updated server component and enhanced fetch capabilities for re

Is it possible to toggle the URL from the getData function? I have my main page component with JSON todos. Can I replace 'todos' with 'users' in my client component? import styles from './page.module.css' import Button from "@ ...

Error: Trying to add an element to an undefined variable (d3 force layout)

I've been racking my brain trying to solve this error I keep encountering while working with a force layout. The problem arose when I switched to reading nodes from a JSON file. When I comment out certain lines, the error disappears. But if I leave th ...

Looking to Identify a Click Within a Complicated Component and Retrieve the Component's ID

Currently, I am working with React for development and have a need to capture clicks at the topmost parent level for performance reasons. const clickHandler = (e) => { console.log("clickHandler", e.target) --> I want to identify the child ...

Trouble with ScrollTo animation on div with adjustable offset top feature - seeking assistance

Having trouble navigating to the correct slide when clicking the right button on the navigation menu. Clicking the menu button displays a list of links. Clicking on a link for the first time will take you to the correct slide, but if you try clicking a dif ...

Is it possible to retrieve the pixel color of a mesh by clicking on it in JavaScript?

On the current page, we have a mesh loaded with TreeJS and displayed in a canvas: https://i.sstatic.net/j8Ztj.png Is there a way to retrieve the color of the point where a click occurs? I attempted a method suggested in this thread: Getting the color val ...

Issue encountered while executing tasks in the Gruntfile.js file

Having trouble with Grunt concatenating my CSS files into one named production.css Below is the output I received from the command prompt: C:\Users\josha\Desktop\Repos\AJAX Project - Grunt Test>grunt C:\Users\josha& ...

Keeping data external to promises in protractor

In my angular app, I have a timeline feature that displays the names and descriptions of players. All player names are under the common class player-title.ng-binding, while all player descriptions share the class .player-description.ng-binding To retrieve ...

Executing a JavaScript function when an element is clicked using inline

Is it possible to write the code below in a single line? <a href="#" onClick="function(){ //do something; return false;};return false;"></a> As an alternative to: <a href="#" onClick="doSomething(); return false;"></a> functio ...

Steps for extracting a specific portion of a value contained within an attribute

In my code, there are multiple hyperlinks with different values attached to an onclick function. Here is an example: <a onclick="Utils.decideOffer('', {'unlockFeature': 'cars'});">cars text</a> <a onclick="Util ...

Having trouble sending a POST request with body parameters in Node.js? The error "undefined req.body.param" might be popping up when you're

I've encountered an issue with my server.js code: const bodyParser = require('body-parser'); const cors = require('cors'); const morgan = require('morgan'); var express = require('express') , http = requir ...

Received a Vue prop as a variable name, rather than the actual string value it represents

In the parent component, my string variable is being passed down. The constant GET_STARTED is equal to the string "Get Started" <script setup> import { GET_STARTED } from '../../constants' import GreenBtn from '@/components/p ...

What are the steps to create a ListView in a ChatApp for organizing and viewing all conversations?

In developing my chat application, I am considering using a List to organize all the chats. Since my app is integrated with Firebase, I am faced with the decision of whether to utilize a FlatList and store all data locally or in a Firebase database. What ...

Steps for creating checkboxes for individual table rows in HTML using embedded PHP and updating their values in a PostgreSQL database:1. Begin by iterating through each

I have already retrieved the data from the database. It is displayed on the HTML table, but it is currently in non-editable mode. I need to ensure that the data shown is accurate and update its Boolean value in the database. Otherwise, incorrect records sh ...

Encountering issues with running an AngularJS application (version 1.6) in Visual Studio following the activation of script

I am new to working on an angular 1.6 application and still learning the ropes. The project consists of an asp.net web api project that needs to be run before starting the angular project. Everything was running smoothly until I tried to debug a parameter ...

Is there a way to ensure my React table consistently returns to the first page?

How can I ensure that my React table always starts at page 1 whenever the search filters are changed? The table currently displays data based on 2 or 3 different filters selected by the user. Each time the filters are updated, the table shows the page numb ...