How to map data into cards react.js - javascript

I'm trying to build a simple shop in react.js.
My next step would be mapping the products which I store in data.js file into separate cards and then a product list. I am using external libraries for Card.
This is data.js (example):
export const data = [
{
id: 1,
title: "example title",
content: "example content",
image: "https://i.imgur.com/example.jpg"
},
{
id: 2,
title: "example title",
content: "example content",
image: "https://i.imgur.com/example.jpg"
},
{
id: 3,
title: "example title",
content: "example content",
image: "https://i.imgur.com/example.jpg"
},
]
That would be a component rendering a single product card:
import React from 'react';
import { Button } from 'react-bootstrap'
import { Card } from '#material-ui/core';
import Col from 'react-bootstrap/Col';
import { data } from '../../../data'
const Product = () => (
<Col xs={12} md={6} lg={4} key={data.id}>
<Card style={{ width: '18rem' }}>
<Card.Header></Card.Header>
<Card.Img variant="top" src={data.image} />
<Card.Body>
<Card.Title>{data.title}</Card.Title>
<Card.Text>
{data.content}
</Card.Text>
<Button variant="primary">Add to cart</Button>
<Button>Add to favs</Button>
</Card.Body>
</Card>
</Col>
)
export default Product;
and finally, the component rendring many products:
import React from 'react';
import Row from 'react-bootstrap/Row';
import {data} from '../../../data'
import Product from '../Product/Product';
import styles from './Shop.module.scss';
const Shop = () => {
return (
<div className='row-wrapper'>
<Row>
{data.map(product => (
<Product key={product.id} {...product} />
))}
</Row>
</div>
)
};
export default Shop;
This does not work, I receive errors in the console. What am I missing?
edit: the error I get:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
stacktrace:
Blockquote
Check your code at Product.js:13.
in Product (at Shop.js:17)
in div (created by Row)
in Row (at Shop.js:15)
in div (at Shop.js:14)
in Shop (created by Context.Consumer)
in Route (at Header.js:24)
in Switch (at Header.js:22)
in div (at Header.js:13)
in Header (at MainLayout.js:15)
in div (at MainLayout.js:13)
in MainLayout (at App.js:12)
in Router (created by BrowserRouter)
in BrowserRouter (at App.js:11)
in App (at src/index.js:6)

You can pass the product details from the shop component to the Product Component through the props, the following code should works:
Product Component
import React from 'react';
import { Button } from 'react-bootstrap'
import { Card } from '#material-ui/core';
import Col from 'react-bootstrap/Col';
const Product = ({product}) => (
<Col xs={12} md={6} lg={4} key={product.id}>
<Card style={{ width: '18rem' }}>
<Card.Header></Card.Header>
<Card.Img variant="top" src={product.image} />
<Card.Body>
<Card.Title>{product.title}</Card.Title>
<Card.Text>
{product.content}
</Card.Text>
<Button variant="primary">Add to cart</Button>
<Button>Add to favs</Button>
</Card.Body>
</Card>
</Col>
)
export default Product;
Shop Component
import React from 'react';
import Row from 'react-bootstrap/Row';
import {data} from '../../../data'
import Product from '../Product/Product';
import styles from './Shop.module.scss';
const Shop = () => {
return (
<div className='row-wrapper'>
<Row>
{data.map(product => (
<Product key={product.id} product={product} />
))}
</Row>
</div>
)
};
export default Shop;

Related

Pass props to navigate for each element of an array with React Router Dom?

I'm trying to pass the props i have on the array.map function i'm using, since the array.map is creating buttons and each one of them navigates to the same screen, i just want to pass them the specific props of each position, like if they click on the button with the id 25 to give the navigate the info that position has, to show it on the next screen
The props look like below. They're on their own file and it's not the whole thing, but it literally has 30 ids so it's way too long and one id gets the idea across.
[
{
id: 1,
num_aula: '1',
horario_retiro: '2:00 ',
año: '1°',
division: '1°',
estado: 'sucio',
},
]
Here's what the code of the Component that's passing props looks like:
import React from "react";
import Button from 'react-bootstrap/Button';
import {aulas} from '../props/aulas';
import Container from 'react-bootstrap/Container';
import { Route, useNavigate } from "react-router-dom";
export default function AdministrarCurso_Portero(){
const navigate= useNavigate();
return(
<Container>
<div className="row">
{/* Acá hay botones que se generan en base a la cantidad de props que haya en el array map
Que te redireccionan a la pantalla de Limpiar Curso, por ahora no le pasa los valores que tenga
*/}
{aulas.map((aula, i) => (
<div key={i} className="col-md-4">
<Button onClick={()=> navigate('/LimpiarCurso',{state: {id:i,num_aula:num_aula,año:año,division:division,horario_retiro:horario_retiro}})}>{aula.año}{aula.division}</Button>
</div>
))}
</div>
</Container>
)
}
And the code from the Component that should receive the props to show them:
import React from "react";
import { View} from 'react-native';
import CheckCircle from '#mui/icons-material/CheckCircle'
import styles from '../../App';
import { GiBroom } from 'react-icons/gi';
import { Route, useLocation, useNavigate } from "react-router-dom";
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Button from 'react-bootstrap/Button';
export default function LimpiarCurso(){
const { state } = useLocation();
const {num_aula, año, division, horario_retiro} = state;
const navigate= useNavigate();
return (
<div>
<Container>
<Row>
<Col></Col>
</Row>
</Container>
<Container>
<Row>
<Col ><CheckCircle sx={{ fontSize: 200, color: 'white', backgroundColor:'green'}} style={{float: 'right'}}/></Col>
<Col ><GiBroom size={200} style={{float: 'right'}}/></Col>
</Row>
</Container>
<Container>
<Row>
<Col ></Col>
<Col><Button onClick={()=> navigate('/AdministrarCurso_Portero')}>Volver</Button></Col>
<Col ></Col>
</Row>
</Container>
</div>
)
}
Maybe there's an easy solution to this, but i haven't really grasped the use of array map or props yet.
Using map is the correct way since you are rendering an array. What you are doing wrong is that you have for example num_aula:num_aula while it should be num_aula:aula.num_aula. Try this:
{aulas.map((aula) => (
<div key={aula.id} className="col-md-4">
<Button onClick={()=> navigate('/LimpiarCurso',{state: {id:aula.id,num_aula:aula.num_aula,año:aula.año,division:aula.division,horario_retiro:aula.horario_retiro}})}>{aula.año}{aula.division}</Button>
</div>
))}

Clicking on IconButton from Material UI causing Errors with Ref?

I am working with Material UI and I am not understanding an error that I am receiving. The error occurs every time that I click on the IconButton component to open up a menu. The menu opens but I get this error:
index.js:1 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Check the render method of `ForwardRef(Menu)`.
in MenuItems (at OMSDashboard.js:67)
in ul (created by ForwardRef(List))
in ForwardRef(List) (created by WithStyles(ForwardRef(List)))
in WithStyles(ForwardRef(List)) (created by ForwardRef(MenuList))
in ForwardRef(MenuList) (created by ForwardRef(Menu))
in div (created by ForwardRef(Paper))
in ForwardRef(Paper) (created by WithStyles(ForwardRef(Paper)))
in WithStyles(ForwardRef(Paper)) (created by Transition)
in Transition (created by ForwardRef(Grow))
in ForwardRef(Grow) (created by Unstable_TrapFocus)
in Unstable_TrapFocus (created by ForwardRef(Modal))
in div (created by ForwardRef(Modal))
in ForwardRef(Portal) (created by ForwardRef(Modal))
in ForwardRef(Modal) (created by ForwardRef(Popover))
in ForwardRef(Popover) (created by WithStyles(ForwardRef(Popover)))
in WithStyles(ForwardRef(Popover)) (created by ForwardRef(Menu))
in ForwardRef(Menu) (created by WithStyles(ForwardRef(Menu)))
in WithStyles(ForwardRef(Menu)) (at OMSDashboard.js:63)
in div (created by ForwardRef(Toolbar))
in ForwardRef(Toolbar) (created by WithStyles(ForwardRef(Toolbar)))
in WithStyles(ForwardRef(Toolbar)) (at OMSDashboard.js:54)
in header (created by ForwardRef(Paper))
in ForwardRef(Paper) (created by WithStyles(ForwardRef(Paper)))
in WithStyles(ForwardRef(Paper)) (created by ForwardRef(AppBar))
in ForwardRef(AppBar) (created by WithStyles(ForwardRef(AppBar)))
in WithStyles(ForwardRef(AppBar)) (at OMSDashboard.js:53)
in OMSDashboard (created by Context.Consumer)
in Route (at App.js:16)
in Switch (at App.js:13)
in App (at src/index.js:8)
in Router (created by BrowserRouter)
in BrowserRouter (at src/index.js:7)
I am not sure what this is referring to. I have provided the code below:
import React, {useState, useEffect, Fragment} from 'react';
import { makeStyles } from '#material-ui/styles';
import AppBar from '#material-ui/core/AppBar';
import Toolbar from '#material-ui/core/Toolbar';
import Typography from '#material-ui/core/Typography';
import Button from '#material-ui/core/Button';
import IconButton from '#material-ui/core/IconButton';
import MenuIcon from '#material-ui/icons/Menu';
import Menu from '#material-ui/core/Menu';
import MenuItem from '#material-ui/core/MenuItem';
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1
},
flex: {
flex: 1
},
menuButton: {
marginLeft: -12,
marginRight: 20
},
appBar: {
marginLeft: '20px',
height: '75px'
},
toolbarMargin: {
minHeight: '75px'
}
})
);
const OMSDashboard = () => {
const classes = useStyles();
const [anchor, setAnchor] = useState(null);
const MenuItems = () => {
return (
<Fragment>
<MenuItem >Profile</MenuItem>
<MenuItem >My Account</MenuItem>
<MenuItem >Logout</MenuItem>
</Fragment>
)};
return (
<Fragment>
<AppBar position="fixed" className={classes.appBar}>
<Toolbar>
<IconButton
className={classes.menuButton}
color="inherit"
aria-label="Menu"
onClick={e => setAnchor(e.currentTarget)}
>
<MenuIcon />
</IconButton>
<Menu
anchorEl={anchor}
open={Boolean(anchor)}
>
<MenuItems />
</Menu>
<Typography
variant="h1"
color="inherit"
className={classes.flex}
>
DashBoard
</Typography>
<Button color="inherit">Menu</Button>
</Toolbar>
</AppBar>
<div className={classes.toolbarMargin} />
<ul>
{new Array(500). fill(null).map((v, i) => (
<li key={i}>{i}</li>
))}
</ul>
</Fragment>
)
}
export default OMSDashboard;
Any kind of help would be greatly appreciated.
I think it's referring on anchor's default value of null. Try removing the null.
Spotted the issue... the problem is not the IconButton itself, it comes from the "relationship" between Menu and MenuItem.
Unfortunately, the only working solution I could find and test successfully was about React.forwardRef for Menu, MenuItem and the IconButton...
1st create your forwardedRef components:
const CustomMenuButton = React.forwardRef((props, ref) => (
<IconButton {...props} buttonRef={ref}>
{ props.children }
</IconButton>));
export default CustomMenuButton;
const CustomMenu = React.forwardRef((props, ref) => (<Menu ref={ref} {...props}>{props.children}</Menu>));
export default CustomMenu;
** Note: ** for this MenuItem you'll have to use innerRef instead:
const CustomMenuItem = React.forwardRef((props, ref) => (<MenuItem innerRef={ref} {...props}>{props.children}</MenuItem>));
export default CustomMenuItem;
2nd: Apply those ones in your code instead:
return (
<Fragment>
<AppBar position="fixed" className={classes.appBar}>
<Toolbar>
<CustomMenuButton
className={classes.menuButton}
color="inherit"
aria-label="Menu"
onClick={e => setAnchor(e.currentTarget)}
>
<MenuIcon />
</CustomMenuButton>
<CustomMenu
anchorEl={anchor}
open={Boolean(anchor)}
>
{/* Does MenuItems "map" the MenuItem inside? */}
{/* In that case, use CustomMenuItem instead for each one! */}
<MenuItems />
</CustomMenu>
<Typography
variant="h1"
color="inherit"
className={classes.flex}
>
DashBoard
</Typography>
<Button color="inherit">Menu</Button>
</Toolbar>
</AppBar>
<div className={classes.toolbarMargin} />
<ul>
{new Array(500). fill(null).map((v, i) => (
<li key={i}>{i}</li>
))}
</ul>
</Fragment>
)
}
export default OMSDashboard;

Warning: Functions are not valid as a React child.This may happen if you return a Component instead of <Component /> from render

I get the above error when I try to display {props.child}.The page remains blank.The detailed warning is
index.js:1 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
in div (at CustomLayout.js:28)
in main (created by Basic)
in Basic (created by Context.Consumer)
in Content (at CustomLayout.js:22)
in section (created by BasicLayout)
in BasicLayout (created by Context.Consumer)
in Layout (at CustomLayout.js:8)
in CustomLayout (at App.js:10)
in div (at App.js:9)
in App (at src/index.js:7)
Below are the project files. Article.js is a component and ArticleListView and CustomLayout are containers to it. I am trying to access the child elements in CustomLayout.js by {props.children}
App.js
import React from 'react';
import './App.css';
import 'antd/dist/antd.css';
import CustomLayout from './containers/CustomLayout'
import ArticleListView from './containers/ArticleListView';
function App() {
return (
<div className="App">
<CustomLayout>
{ArticleListView}
</CustomLayout>
</div>
);
}
export default App
ArticleListView.js
import React from 'react'
import Article from '../components/Article'
class ArticleListView extends React.Component{
render(){
return(
<Article/>
);
}
}
export default ArticleListView
Article.js
import React from 'react'
import { List, Avatar, Icon } from 'antd';
const listData = [];
for (let i = 0; i < 23; i++) {
listData.push({
href: 'http://ant.design',
title: `ant design part ${i}`,
avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
description:
'Ant Design, a design language for background applications, is refined by Ant UED Team.',
content:
'We supply a series of design principles, practical patterns and high quality design resources (Sketch and Axure), to help people create their product prototypes beautifully and efficiently.',
});
}
const IconText = ({ type, text }) => (
<span>
<Icon type={type} style={{ marginRight: 8 }} />
{text}
</span>
);
function Article(props){
return(
<List
itemLayout="vertical"
size="large"
pagination={{
onChange: page => {
console.log(page);
},
pageSize: 3,
}}
dataSource={listData}
footer={
<div>
<b>ant design</b> footer part
</div>
}
renderItem={item => (
<List.Item
key={item.title}
actions={[
<IconText type="star-o" text="156" key="list-vertical-star-o" />,
<IconText type="like-o" text="156" key="list-vertical-like-o" />,
<IconText type="message" text="2" key="list-vertical-message" />,
]}
extra={
<img
width={272}
alt="logo"
src="https://gw.alipayobjects.com/zos/rmsportal/mqaQswcyDLcXyDKnZfES.png"
/>
}
>
<List.Item.Meta
avatar={<Avatar src={item.avatar} />}
title={<a href={item.href}>{item.title}</a>}
description={item.description}
/>
{item.content}
</List.Item>
)}
/>
);
}
export default <Article/>
CustomLayout.js
import React from 'react'
import { Layout, Menu, Breadcrumb } from 'antd';
const { Header, Content, Footer } = Layout;
function CustomLayout(props){
return(
<Layout className="layout">
<Header>
<div className="logo" />
<Menu
theme="dark"
mode="horizontal"
defaultSelectedKeys={['2']}
style={{ lineHeight: '64px' }}
>
<Menu.Item key="1">nav 1</Menu.Item>
<Menu.Item key="2">nav 2</Menu.Item>
<Menu.Item key="3">nav 3</Menu.Item>
</Menu>
</Header>
<Content style={{ padding: '0 50px' }}>
<Breadcrumb style={{ margin: '16px 0' }}>
<Breadcrumb.Item>Home</Breadcrumb.Item>
<Breadcrumb.Item>List</Breadcrumb.Item>
<Breadcrumb.Item>App</Breadcrumb.Item>
</Breadcrumb>
<div style={{ background: '#fff', padding: 24, minHeight: 280 }}>{props.children}</div>
</Content>
<Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by Ant UED</Footer>
</Layout>
);
}
export default CustomLayout
If you are using any javascript expression then only use curly braces like - {a+b}.
but form html tags or react component you need to import as per react standard.
Use like this
<CustomLayout>
<ArticleListView />
</CustomLayout>
and change your export default <Article/> to export default Article
It should be <ArticleListView/>, not {ArticleListView}
Try
<CustomLayout>
<ArticleListView />
</CustomLayout>
rather than
<CustomLayout>
{ArticleListView}
</CustomLayout>
in javascript we work like isConditionTrue ? screenOne :screenTwo
but in typescript we have to change isConditionTrue ? :

How to set a HTML element ID on a material-ui component?

I have a website built with Gatsby.js using the Material-UI.
Specific problem is this: I want to use the Google Tag Manager "Element Visibility" triggers. If some HTML element becomes visible, GTM should fire some GA tag.
Question is this: how can I specify the HTML ID for a material-ui component for GTM (or anything else) to find it?
First example:
// ...react imports omitted...
import makeStyles from '#material-ui/core/styles/makeStyles';
import Box from '#material-ui/core/Box';
import Grid from '#material-ui/core/Grid';
import CloseIcon from '#material-ui/icons/Close';
import Link from '~components/Link';
import ButtonSubmit from '~components/form-buttons/ButtonSubmit';
import Container from '~components/Container';
// ... all other imports are in-house code
const useStyles = makeStyles(theme => ({ /* ...styles... */}));
const GuestUserSoftSaleSecondPopup = ({ which, ...rest }) => {
const classes = useStyles();
// ...setup code omitted...
return (
<Box bgcolor="#474d5c" width="100%" py={4} className={classes.banner}>
<Container>
<Grid container direction="row" justify="space-between" alignItems="center" spacing={2}>
<Grid item xs={12} sm={1} md={3} lg={4}>
<CloseIcon onClick={handleClose} size="large" className={classes.closeIcon} />
</Grid>
<Grid item xs={12} sm={7} md={5} lg={4}>
<Link to="/subscribe" variant="h5" className={classes.linkStyle}>
Become a member for full access
</Link>
</Grid>
<Grid item xs={12} sm={4} className={classes.buttonPosition}>
<Link to="/subscribe" underline="none" className={classes.linkStyle}>
<ButtonSubmit type="button" fullWidth={false}>
See my option
</ButtonSubmit>
</Link>
</Grid>
</Grid>
</Container>
</Box>
);
};
// ...proptypes and `export` clause
Second example:
// ...react imports omitted...
import makeStyles from '#material-ui/core/styles/makeStyles';
import MuiDialog from '#material-ui/core/Dialog';
const useStyles = makeStyles(() => ({ /* ...styles... */ }));
const Dialog = ({ children, background, backdrop, isOpen, ...rest }) => {
const classes = useStyles({ background });
return (
<MuiDialog
open={isOpen}
maxWidth="sm"
fullWidth
disableBackdropClick
disableEscapeKeyDown
BackdropProps={{
className: backdrop ? classes.backdropBM : classes.backdrop
}}
PaperProps={{
className: classes.paper
}}
scroll="body"
{...rest}
>
{children}
</MuiDialog>
);
};
If you look at the API documentation for almost any of the Material-UI components, you will find at the end of the "Props" section a statement like the following example from Dialog:
Any other props supplied will be provided to the root element (Modal).
This means that any props not explicitly recognized by this component will be passed along eventually to whatever HTML element is the outermost element rendered. So for most Material-UI components, in order to add an id property, you just specify it.
My example below (a modification of the Simple Dialog demo) includes three different ids: one on the Dialog element which will be placed on the outermost div of the Modal, one specified via the PaperProps which will go on the main Paper div of the visible content of the dialog, and one on the Box wrapped around the dialog content.
import React from "react";
import PropTypes from "prop-types";
import { makeStyles } from "#material-ui/core/styles";
import Button from "#material-ui/core/Button";
import Avatar from "#material-ui/core/Avatar";
import List from "#material-ui/core/List";
import ListItem from "#material-ui/core/ListItem";
import ListItemAvatar from "#material-ui/core/ListItemAvatar";
import ListItemText from "#material-ui/core/ListItemText";
import DialogTitle from "#material-ui/core/DialogTitle";
import Dialog from "#material-ui/core/Dialog";
import PersonIcon from "#material-ui/icons/Person";
import Typography from "#material-ui/core/Typography";
import { blue } from "#material-ui/core/colors";
import Box from "#material-ui/core/Box";
const emails = ["username#gmail.com", "user02#gmail.com"];
const useStyles = makeStyles({
avatar: {
backgroundColor: blue[100],
color: blue[600]
}
});
function SimpleDialog(props) {
const classes = useStyles();
const { onClose, selectedValue, open } = props;
const handleClose = () => {
onClose(selectedValue);
};
const handleListItemClick = value => {
onClose(value);
};
return (
<Dialog
onClose={handleClose}
aria-labelledby="simple-dialog-title"
open={open}
PaperProps={{ id: "MyDialogPaperID" }}
id="ThisIDWillBeOnTheModal"
>
<DialogTitle id="simple-dialog-title">Set backup account</DialogTitle>
<Box id="MyBoxID">
<List>
{emails.map(email => (
<ListItem
button
onClick={() => handleListItemClick(email)}
key={email}
>
<ListItemAvatar>
<Avatar className={classes.avatar}>
<PersonIcon />
</Avatar>
</ListItemAvatar>
<ListItemText primary={email} />
</ListItem>
))}
</List>
</Box>
</Dialog>
);
}
SimpleDialog.propTypes = {
onClose: PropTypes.func.isRequired,
open: PropTypes.bool.isRequired,
selectedValue: PropTypes.string.isRequired
};
export default function SimpleDialogDemo() {
const [open, setOpen] = React.useState(false);
const [selectedValue, setSelectedValue] = React.useState(emails[1]);
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = value => {
setOpen(false);
setSelectedValue(value);
};
return (
<div>
<Typography variant="subtitle1">Selected: {selectedValue}</Typography>
<br />
<Button variant="outlined" color="primary" onClick={handleClickOpen}>
Open simple dialog
</Button>
<SimpleDialog
selectedValue={selectedValue}
open={open}
onClose={handleClose}
/>
</div>
);
}
Material UI components don't let you set an id for them since the implementation inside should be a black box and may contain multiple html element. See if you can wrap the element in a div and put the id on that instead.
Another option would be to add a class (via the classes prop) to the element instead but I'm not sure if Google Tag Manager can use those instead of ids.

How to set the style a react.js component when creating it?

How to set the style a react.js component when creating it?
Below is some of my code (partially inherited from a stronger developer and then simplified for brevity).
I want to re-use my LogComponent to print several pages of a Log. However, in some cases I want to force a particular width on the returned List, rather than allowing it to flex as it sees fit.
I would prefer to not define a separate LogComponentFixed or to have an if (...) {return (...)} else {return(...)} in my LogComponent.
I have in mind to do something in Log.js like:
<LogComponent heading={"Page 1"}, lines={page_1}, style={styles.list_1} />
<LogComponent heading={"Page 1"}, lines={page_1}, style={styles.list_2} />
And to then, in LogComponent do something like:
<List style={style}> ... </List>
I also tried using something like
<List className={list_1}> ... </List>
But none of the things I've tried works...
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)
Here you are sending the styles as a prop to LogComponent, that's why it will not be applied as styles to that component you have created. The style attribute is for HTML tags and in material-ui, you can pass styles to a wrapper component also.
In your case you can get the styles inside your LogComponent as below:
Send styles as a prop as you mentioned in the question
<LogComponent heading={"Page 1"}, lines={page_1}, style={styles.list_1} />
Now, you can access it from props,
// right below get the style
const LogComponent = ({classes, list_class, heading, lines, style}) => {
return (
<div className={classes.root} style={style}> // Look style attribute added, style(value) is 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>
)
}

Categories