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

Oops! The `source` prop provided to the `Image` component in React Native is invalid

Is it possible to receive assistance in React Native? I keep getting this error from the compiler: "Failed prop type: Invalid prop source supplied to Image" The 'dec' variable is a string fetched from an API. Please provide some guida ...

Is it feasible to amalgamate the states of several child components into a single parent component state in NextJS/React?

Issue I am faced with the challenge of handling multiple Child components that can pass their state to a Parent component. Now, I am looking to render several Parent components within a Grandparent component and merge the states of each Parent into a sing ...

Combining various functions into a single button

I am currently working on creating a full-screen menu that functions like a modal. Everything seems to be working fine, except for the fadeOut animation. Can someone please help me understand what is causing issues with my scripts/codes? I want the content ...

Displaying the information from a nested array of objects in an HTML table through iteration

In the code snippet below, there is an input with a nested array of objects. The main array of objects is called summary and within it, there's a nested array called run_type. let input = { "summary": [ { " ...

Why is the inline-block element in the list displaying on two lines? The text contains a number, but does it affect the layout?

What could be the reason for 'Maroon 5' moving down to a second line? Despite adding extra characters and testing with an integer, the issue persists. <ul id="soundsLike"> <li>Foo Fighters</li> <li>Maroon 5</ ...

Is there a way to position the button at the bottom right corner of my div box?

Having trouble positioning the button in the bottom-right corner of the parent div? I attempted using float: right;, but it ended up outside of the box. How can I keep the button within the box and align it to the bottom-right corner? If you have a solutio ...

Issues with Grunt functionality after installation on Ubuntu

I successfully installed Grunt by running the following commands in the terminal: sudo apt-get install nodejs sudo apt-get install npm npm install -g grunt-cli After executing npm install -g grunt-cli, here is the output from the terminal: (output he ...

The Selenium driver's execute_script() function is not functioning as expected

When I attempt to execute a JavaScript using driver.execute_script, nothing happens and the system just moves on to the next line of Python code. Any ideas? I've been web scraping on a webpage, using JavaScript in the Console to extract data. The Jav ...

Ensure that divs can adjust in size while maintaining the same dimensions of their contained

I'm currently facing a slight issue with these two divs. I want them to be scalable, which I know can be achieved by using percentages, but every time I do so, the divs end up out of position. When I try setting widths, they look fine in Google Chrome ...

What could be causing my Material UI Divider to appear invisible within a Material UI Container or Paper component?

Hey there! I am absolutely smitten with Material UI - it's incredibly versatile. However, I'm facing a bit of trouble with the Material UI Divider not displaying when nested within either a Container or Paper component. I've looked into it ...

A declaration of "import '***.css';" was located within an ECMAScript module file in the monaco-editor npm library

It's perplexing to me why the developers of monaco-editor included these statements, as they are actually causing errors in my browser such as: Failed to load module script: Expected a JavaScript module script but the server responded with a MIME typ ...

Leveraging and utilizing TypeScript npm packages

My goal is to create shared code in TypeScript, package it as an npm package, and easily install it. I attempted to create an external library like this: export class Lib { constructor(){ } getData(){ console.log('getting data from l ...

Javascript handling scrolling and repositioning

When using the scrollBy() method in the window object of JavaScript, there are two arguments required. But what do these arguments actually represent? The resource I am currently studying from states that it is "the number of pixels to scroll by," but I am ...

What is the process for uploading files with just node.js?

My dilemma involves a webpage featuring a form with a file input field. Upon submitting the form, I wish for the server to write the file on the server side. Despite numerous attempts to upload various test images using this form, each results in a plain ...

Utilizing CSS for styling a specific class in a Joomla Module

Recently, I was working on a Joomla Module and came across an interesting issue. When inspecting the CSS using Firebug, I noticed that there were multiple nested divs within the module, each with its own class. One example of this structure looked like: & ...

The setStyle() method in JavaFX is like CSS Selectors

Is it possible to bind CSS files to style JavaFX components and also change properties dynamically in code? I'm struggling with the setStyle() method as there's limited documentation available on how to use it effectively. Instead of modifying t ...

Sharing information between different components in React can be done using props, context, or a

When attempting to edit by clicking, the parent information is taken instead of creating a new VI. I was able to achieve this with angular dialog but I am unsure how to do it with components. This is done using dialog: <div class="dropdown-menu-item" ...

Are you experiencing issues with the map displaying inaccurate latitude and longitude when clicking on a specific point?

I've successfully created a simple polyline on Google Maps and attached a click event listener to it. However, I'm encountering an issue where clicking on the line provides me with latitude and longitude coordinates that point to Canada, even th ...

Semantic-UI-react sticky sidebar

I have searched extensively on Google, reviewed semantic ui's documentation and issues page, and also checked Stack Overflow but could not find a solution to my problem. My question is related to Semantic-ui-react - how can I create a sidebar with fi ...

Executing multiple AJAX calls at the same time in PHP

I have a puzzling question that I can't seem to easily solve the behavior of this situation There are two ajax call functions in my code: execCommand() : used for executing shell commands through PHP shell_exec('ping 127.0.0.1 > ../var/log/ ...