What is the best way to customize the style of a react.js component upon its creation?

Is there a way to set the style of a react.js component during its creation?

Here is a snippet of my code (which I inherited and simplified for clarity)

I want to be able to use my LogComponent to display different pages of a Log. However, in certain instances, I need to enforce a specific width on the displayed list instead of allowing it to adjust automatically.

I would rather not create a separate LogComponentFixed or include conditional statements within my LogComponent.

My idea is to do something like this in Log.js:

<LogComponent heading={"Page 1"}, lines={page_1}, style={styles.list_1} />
<LogComponent heading={"Page 1"}, lines={page_1}, style={styles.list_2} />

Then in LogComponent, I can do something like:

<List style={style}> ... </List>

I also attempted to use something similar to:

<List className={list_1}> ... </List>

But none of my attempts seemed to work...

Log.js

import React from 'react'
import Typography from '@material-ui/core/Typography'
import { withStyles } from '@material-ui/core/styles'
import LogComponent from './LogComponent'

const styles = theme => ({
  title: {
    padding: theme.spacing.unit*1.5,
  },
  list_1: {
  },
  list_2: {
    width: "300px"
  },
  listContainer: {
    flexGrow: 1,
    minHeight: 0,
    overflow: 'auto'
  },
})

const Log = ({classes, log}) => {
  const page_1 = log[0];
  const page_2 = log[1];
  return (
    <div>
      <Typography className={classes.title} color="textSecondary" key={1}>
        Example Log
      </Typography>
      <div className={classes.listContainer} key={2}>
        <LogComponent heading={'Page 1'} lines={page_1} />
        <LogComponent heading={'Page 2'} lines={page_2} />
      </div>
    </div>

export default withStyles(styles)(Log)

LogComponent.js

import React from 'react'
import Typography from '@material-ui/core/Typography'
import { withStyles } from '@material-ui/core/styles'
import { List, ListItem, ListItemText } from '@material-ui/core';

const styles = theme => ({
  title: {
    padding: theme.spacing.unit*1.5,
  },
}

const LogComponent = ({classes, list_class, heading, lines}) => {

    return (
    <div className={classes.root}>
    <Typography className={classes.title} color="textSecondary" key={1}>
            {heading}
            </Typography>
            <div>
            <List dense>
                {[...lines[0]].map(e => 
                <ListItem><ListItemText primary={e} /></ListItem>
                )}
            </List>
            </div>                    
    </div>
    )
}

export default withStyles(styles)(LogComponent)

Answer №1

By passing the styles as a prop to LogComponent, they will not be applied directly to the component you created. Remember, the style attribute is meant for HTML tags and in material-ui, you have the option to pass styles to a wrapper component.

To ensure the styles are received by your LogComponent, follow this approach:

Include styles as a prop as described in your query

<LogComponent heading={"Page 1"}, lines={page_1}, style={styles.list_1} />

Once implemented, access the styles from props like so:

                                                   // right below get the style
const LogComponent = ({classes, list_class, heading, lines, style}) => {

return (
<div className={classes.root} style={style}> // Note: style attribute added with value from props
<Typography className={classes.title} color="textSecondary" key={1}>
     {heading}
     </Typography>
     <div>
     <List dense>
          {[...lines[0]].map(e => 
                <ListItem><ListItemText primary={e} /></ListItem>
           )}
      </List>
      </div>                    
    </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

An error is thrown when trying to use an imported function from Next.js in the getServerSideProps function, resulting in a 'Reference

In my project, I am utilizing Firebase for authentication. Once the user successfully authenticates, I store their id token in cookies. This allows me to validate the token server-side for Server-Side Rendering (SSR) whenever any request is made to a page ...

Having trouble with npm command while trying to install Radium

Issue with installing Radium npm install --save radium Error Message: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree ... npm ERR! See C:\Users\Max\AppData\Local\npm-cache\eresolve-report.txt for a ...

Tips on changing the URL of the current tab after clicking on a link

const selenium = require('selenium-webdriver'); require('chromedriver'); const By = selenium.By; const driver = new selenium.Builder().forBrowser('chrome').build(); const url = 'https://example.com'; driver.get(url) ...

Loop through a JSON object within the collection of another ng-repeat loop

I'm facing an issue with my ng-repeat loop where I iterate through a JSON and display it in a table. The problem is that when I try to iterate through a nested JSON value, it's treating it as a string. <tr ng-repeat="(key,value) in event. ...

Troubleshooting: Unable to load template file content in AngularJS ng-view

Setting up a demo angular app has been quite the challenge for me. Despite my efforts, the content from my partial file (partials/test.html) is not loading into the layout file as expected. Below is a snippet of my index.html: <!DOCTYPE html> <ht ...

forming a boundary that stands alone, unattached to any other boundaries

I am trying to design a navigation bar that resembles the one depicted in the image provided. The concept involves creating a navigation bar where each border is separated from the others, potentially achieved using hr tags. However, I am struggling to fi ...

Experiencing odd behavior with my Dash App when using CSS grid on it

Seeking assistance with my coding issue, I believe sharing my code from Github would be the most efficient way to address it. An exclusive branch named css_problem_branch has been created to showcase the problem at hand. To access the Github repository, p ...

What is the correct method for launching a modal window in wagtail-admin?

I am currently working on enhancing my wagtail-admin interface, but I have hit a roadblock when trying to open a modal window. While I could create a div with a close button, I believe there must be a more appropriate method for achieving this. It seems th ...

What is the method for setting the direction of the label in an MUI outlined Textfield

My setup involves using MUI version 4 with an RTL theme by setting direction: 'rtl' within the theme itself. Everything seems to be working well except when I try to use an outlined TextField - oddly enough, the value appears aligned RTL but the ...

Polymerfire: Unable to locate a default bucket

Having an issue with uploading data to the storage Bucket of my app. The line var uploadRef = firebase.storage().ref(); is triggering this error message: Firebase Storage: No default bucket found. Ensure the 'storageBucket' property is set when ...

In MUI v5 React, the scroll bar vanishes from view when the drawer is open

Currently, I am working on developing a responsive drawer in React using mui v5. In the set-up, the minimum width of the drawer is defined as 600px when it expands to full width. However, an issue arises when the screen exceeds 600px - at this point, the d ...

Do css classes consistently provide a solution to issues with style overrides?

Would it be more beneficial to utilize css .class instead of #id to avoid issues with style overriding and importance? #content ul li a {font-size:10px} #content .demo ul li a {font-size:15px} ...

Rowing and Columning with Bootstrap

Hey there! I'm currently working on creating some stylish boxes to showcase text and possibly an image background. However, I'm encountering an issue where the boxes are not aligning correctly on smaller screens. https://i.sstatic.net/JoYtj.jpg ...

Transmit Data Efficiently Using Axios

Having an issue where when sending multiple data with axios, the image in formdata does not send. However, when I only send the formdata it works fine. If anyone knows how to successfully send multiple data in axios, please provide a solution. const onS ...

Utilizing Async.each fails to trigger the ultimate callback function

Here's the scenario: I expect the function finalCallBack to be triggered after we finish looping through all elements. var rows = [ { name: 'first'}, { name: 'second'} ]; var execForEachRow = function(row, callback){ var ...

Troubleshooting MongoDB query criteria in Meteor and JavaScript doesn't yield the expected results

I am encountering an issue with a Products collection that has an attribute called "productCode". My goal is to create a server-side query to fetch a product based on the productCode attribute. Unfortunately, I keep running into a "cannot read property &ap ...

What causes the re-rendering when setting the same value?

https://i.stack.imgur.com/LWvlR.png What is causing the excessive re-renders in this function component? I understand that function components are checked with the Object.is method and only re-render if the result is false. So why is this error happening ...

I am interested in creating a text box that has the ability to gather user input and connect it to a search

I have been attempting to develop a text box that can collect answers and link them with the search URL. However, I am encountering issues where even though I can input text into the textbox, it is not being recognized by the script. The error message sh ...

What role does a promise play in rendering code asynchronous?

While we often use promises to avoid the dreaded function callback hell, a question remains: where exactly in the event loop does the promise code execute and is it truly asynchronous? Does the mere fact that the code is within a promise make it asynchron ...

Tips for maintaining authentication in a Next.js application with Firebase even when tokens expire or the page is refreshed

Struggling with firebase authentication flows while building an app using firebase and next.js. Everything was going smoothly until I encountered a bug or error. When my computer remains logged in to the app for some time and I refresh the page, it redirec ...