What is the best way to dynamically pass props to the styles hook in Material UI?

Looking for a way to dynamically add background images to div elements? I'm currently iterating over an array of objects and returning divs, but I'm not sure how to set the background image based on the image URL in each object. Can anyone help me with this?

Below is the code snippet:

const useStyles = makeStyles({
div: (props) => ({
width: "100px",
height: 0,
paddingBottom: "100px",
backgroundImage: "how can I determine which image to display",
 }),
});

let arr = [
       { photo_url: "some url" },
       { photo_url: "some url" },
       { photo_url: "some url" },
       ];

function Test() {
   const classes = useStyles("how can I provide the image for each object here");
   return arr.map((obj) => <div className={classes.div}></div>);
   }

Note: To keep it simple, I've used the style prop to handle dynamic styling and the className prop for generic styles shared by all divs.

Answer №1

Pass the array as an argument to useStyles function:

   const classes = useStyles(array);

Within the makeStyles function, access the array:

  const useStyles = makeStyles(array=>{
    let divStyles={} 

// Generate dynamic styles based on the index of the .div class:

  array.forEach((bgUrl,index)=>{
      divStyles[`&:nth-child(${index+1})`]={ // considering the zero-based indexing
        width: "100px",
        height: 0,
        paddingBottom: "100px",
        backgroundImage: bgUrl,
         }
  })
  return {div:divStyles}
});

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

image animation in jquery not functioning properly

I'm attempting to create an image that fades in from the left upon loading until it reaches a certain point on the screen. Despite thinking my code is correct, nothing is happening. Can someone please assist me with this issue? Here is the function I ...

What is the best way to include multiple ng-repeats within a single ng-repeat?

Hey, I'm facing quite a tricky situation with this grid and could use some assistance. I'm trying to figure out how to populate the data using ng-repeat. I've attached an image showcasing the desired layout of the grid and the order in which ...

Transfer a PHP variable between pages to retrieve the appropriate item from a button

In my project, I have two pages named content.php and pagecontent.php. In content.php, I am fetching product information from a database and displaying it in table format. The table has a grid layout with 2 rows and 3 columns. Each cell contains the descri ...

Unable to modify the style of a deeply embedded component within Material-UI's Jss styling

When using Material-UI's ExpansionPanelSummary component, you have the ability to include an icon inside it by utilizing the expandIcon prop and customize its style using the expandIcon css class. Examining the component's implementation, we ca ...

What is the process for incorporating the Angular JS $q service into this specific scenario?

Looking at the example below, it's essential to ensure that the drawFunc method completes before proceeding to add the opacity and ultimately including foregroundPath to the Kinetic layer. Is there a way to effectively "wait" for the value of foregro ...

How to Stop Render by Clicking Draw?

Check out the example below: https://codesandbox.io/s/musing-lumiere-8uct78 In this scenario, each time you click on Draver on the left side and select Home, the Home component renders every time Draver is opened. Is there a way to pause this processing? ...

When using JQuery, data may not be displayed in another function even when using the same command

Hello, I'm new here and encountering a strange problem with two functions in my script. Let me show you the first function: $(document).on("click", "#result2 p", function(){ var inv_id = $(this).text(); $.get("autocomplete_inv.php", ...

How can buttons be placed dynamically next to each other using Bootstrap?

I currently have the following code snippet: <div class="button-box col-lg-12"> <a href="mylink.php" class="btn btn-info" role="button">About Us</a> <a href="mylink.php" class=& ...

Looking to trigger the Enter key press with .sendKeys(Keys.ENTER); on something other than a text field

There is a unique element on the page which is neither a text box nor a button, it consists of a list of items. Strangely, pressing enter on the webpage causes my list of orders to disappear from the user interface. I attempted to utilize driver.findEleme ...

How come the 'color' property in the material-ui TextField functions properly, while the 'borderColor' property does not work as expected?

I am trying to show a TextField in orange color: <TextField id={field_meta.name} label={field_meta.title} defaultValue={field_meta.value? field_meta.value: ""} onChange={this.handleChange} margin="normal" inputProps={{style: {bo ...

Utilize an npm package to transform a CSS file into inline styles within an HTML document

I have an HTML file with an external CSS file and I would like to inline the styles from the external style sheet into one inline <style> tag at the top of the head. Any assistance would be greatly appreciated. Note: I do not want to use the style a ...

Internet Explorer 8 is causing alignment problems with sidebars on certain websites within a Wordpress multisite setup

I am managing a Wordpress multisite setup with the following websites: The main portal: which connects to The issue arises on all pages of gprgebouw.nl and gpradvies.nl but not on the other domains. Attached is a screenshot of the homepage of gprgebouw. ...

Error SCRIPT438: The function 'formatCurrency' is not supported by this object

I'm encountering an "SCRIPT438: Object doesn't support property or method 'formatCurrency'"" error when attempting to format currency for cells within a jQuery datatable using the jQuery formatCurrency library. Below is the code snippe ...

All pictures aligned with overflow

The first container is working fine, displaying 2 images vertically, but when there are 6 images, it overflows. The problem lies with container 2, where I want to create a horizontal list of images with overflow (only horizontal). This is the current sta ...

What is the best way to deactivate certain JavaScript functions on my webpage when accessed through a mobile device?

Is there a way to disable specific JavaScript functions when accessing my website from a mobile device? While I can achieve this using CSS only, certain buttons require JavaScript functionality. Below is the internal JavaScript code: var menuBtn = docume ...

Vue JS Image Path

I have a Vue.js structure file that looks like this: --assets ----image ------my-image.png ------my-image2.png --components ----user ------userStart.vue To display the images using an array object, my code in userStart.vue is as follows: ...

Arrange JSON response data in alphabetical order

Looking to sharpen my skills by working with public APIs in JavaScript. My goal is to sort the list of items alphabetically by the h4 value (food name) when the query is submitted. I attempted to use .sort() on the response item before using .map(), but en ...

Guide to disabling file system routing for a particular page in Next.js

I'm trying to figure out how to block file system routing for only one specific page in nextjs. Despite attempting to use a Custom Server, the useFileSystemPublicRoutes : false option doesn't seem to work as some pages are still accessed through ...

Transfer files using Ajax and FormData technique

I have extensively researched various topics on this issue and prefer not to rely on any external plugins. function addToDatabase(menuItem){ var formData = new FormData(); formData.append("Description", document.getElementById("DescriptionID").value); ...

Resolution for Reflected Diagonal Backdrop Design

Encountering a bug in Firefox with my mirrored diagonal background pattern. A vertical line appearing between left and right positioned elements at certain screen widths. Seeking a CSS solution or hack, no linked image files allowed. .stripes-background ...