Unable to pass down useState props for adding count - javascript

I have three components im trying to connect together to add the number of items I have in a shopping cart. I have the main component which creates the CartCount object and setCartCount functionality:
function MinerStore() {
const [cartCount, setCartCount] = useState([0]);
const addToCart = () => {
setCartCount(cartCount + 1);
};
return (
<>
<div >
<StoreNav cartCount={cartCount} />
<div>
<StoreCard addToCart={addToCart} />
</div>
</div>
</>
);
}
I also then have the two components I am trying to show the added count on as well as the added count functionality:
export default function StoreCard(addToCart) {
return (
<ThemeProvider theme={theme}>
<main>
<Container>
<Grid container spacing={3}>
{data.map((data) => (
<Grid item key={data.id} xs={12} sm={6} md={3}>
<Card>
<CardContent>
</CardContent>
<CardActions>
<div>
<Button onClick={addToCart}>
Add to Cart
</Button>
</div>
</CardActions>
</Card>
</Grid>
))}
</Grid>
</Container>
</main>
</ThemeProvider>
);
}
export default function StoreNav(cartCount) {
return (
<AppBar position="static">
<Toolbar>
<IconButton>
<Badge badgeContent={cartCount} color="primary">
<ShoppingCartIcon />
</Badge>
</IconButton>
</Toolbar>
</AppBar>
);
}

You've set your initial state as an array [0].
Set it as as 0 and check it out
And ofc as the people above mentioned you should either use props or {addToCart} in the child's parameter.
Then on button should look as such:
<Button onClick={addToCart /* or props.addToCart */}>Add to Cart </Button>

Related

setState hook does not set value

I'm triggering setClickedMovieId using onClick event. I also use useEffect to check if the value of state is set correctly, however, it consoles out the default value (zero).
I need to save the id of a clicked item in order to be able to use it at <NavLink to={"movie/" + clickedMovieId}>.
const MovieCards = () => {
const { movies } = useContext(MoviesContext);
const [clickedMovieId, setClickedMovieId] = useState<number>(0);
useEffect(() => {
console.log('Current value of movie id state', clickedMovieId);
}, [clickedMovieId]);
return (
<div >
<Grid container spacing={1}>
{movies.map((movie) => (
<Grid item xs={6} sm={2} key={movie.id}>
<NavLink to={"movie/" + clickedMovieId}>
<Card className="card">
<CardActionArea>
<CardMedia
component="img"
/>
</CardActionArea>
<CardActions>
<Button size="small" color="primary">
<FavoriteBorderIcon />
</Button>
<Button size="small" color="primary" onClick={() => setClickedMovieId(movie.id)}>
{movie.rating}
</Button>
</CardActions>
</Card>
</NavLink>
</Grid>
))}
</Grid>
</div>
);
}
export default MovieCards;
How can I fix it?
Thanks!
Solution:
<NavLink to={"movie/" + movie.id}>

ReactJS- Calling a dynamic link based on a prop value

i have a cards.js which has the following function. Now the calling method passes three values . header1, header2 and Link (this is the *.js page that has to be called)
export default function Cards(props) {
const classes = useStyles();
return (
<div className="App">
<Card className={classes.card} variant="outlined">
<CardContent>
<Typography
variant={"h5"}
gutterBottom
>
{props.header1}
</Typography>
<Typography
variant={"caption"} >
{props.header2}
</Typography>
<Divider className={classes.divider} light />
<Button variant="contained" color="secondary" onClick={()=> (call either link1.js or link2.js )}>
Lets goooooo!
</Button>
</CardContent>
</Card>
</div>
);
}```
calling method
class UIM extends Component {
render() {
return (
<div className="text-page">
<Grid container alignItems="center" justify="space-evenly" >
<Grid ><Cards header1="card 1 for a task1" header2="click text2" link="link1"/></Grid>
<Grid ><Cards header1=" card 2 for task 2" header2=" click text 2" link="link2"/></Grid>
</Grid>
</div>
)
}
}
I am new to react and learning right now, so wondering if such a thing is possible or should i use router to route to different pages (ie. call either link1.js or link2.js ) ??
I found out by by adding pathname:props.link i can get the button to link to multiple locations within the material ui button.
<Card className={classes.card} variant="outlined">
<CardContent>
<Typography
variant={"h5"}
gutterBottom
>
{props.header1}
</Typography>
<Typography
variant={"caption"} >
{props.header2}
</Typography>
<Divider className={classes.divider} light />
<Button variant="contained" color="secondary">
<NavLink to={{pathname:props.link}}>Lets goooooo!</NavLink>
</Button>
</CardContent>
</Card>

React rendering issue with material-ui library

I’m having an issue with React and using the material-ui library. My cards are getting rendered vertically instead of side by side horizontally. I tried messing around with the react grid component but it didn’t help.
Output:
Expected:
Here is the original code that perfectly renders cards side by side: https://github.com/acm-uic/roll-call/blob/feature/home-page/src/App.tsx
return (
<React.Fragment>
<CssBaseline />
<AppBar position="relative">
<Toolbar>
<Typography variant="h6" color="inherit" noWrap>
ACM Roll Call
</Typography>
</Toolbar>
</AppBar>
<main>
{/* Hero unit */}
<div className={classes.heroContent}>
<Container maxWidth="sm">
<Typography component="h1" variant="h2" align="center" color="textPrimary" gutterBottom>
ACM Roll Call
</Typography>
<Typography variant="h5" align="center" color="textSecondary" paragraph>
The Association for Computing Machinery Student Chapter at the University of Illinois at Chicago (ACM#UIC) is a community for all UIC students interested in computing, computing machinery and related technologies.
</Typography>
</Container>
</div>
<Container className={classes.cardGrid} maxWidth="md">
{/* End hero unit */}
<Grid container spacing={4}>
{cards.map(card => (
<Grid item key={card} xs={12} sm={6} md={4}>
<Card className={classes.card} raised>
<CardMedia
className={classes.cardMedia}
image="https://avatars3.githubusercontent.com/u/20177515?s=280&v=4"
title="Image title"
/>
<CardContent className={classes.cardContent}>
<Typography gutterBottom variant="h5" component="h2">
Event Name
</Typography>
<Typography>
This is a media card. You can use this section to describe the content.
</Typography>
</CardContent>
<CardActions>
<Button size="small" color="primary">
View
</Button>
<Button size="small" color="primary">
Edit
</Button>
</CardActions>
</Card>
</Grid>
))}
</Grid>
</Container>
</main>
{/* Footer */}
<footer className={classes.footer}>
<Typography variant="h6" align="center" gutterBottom>
ACM Roll Call
</Typography>
<Typography variant="subtitle1" align="center" color="textSecondary" component="p">
Attendance tracking for events and meetings
</Typography>
</footer>
{/* End footer */}
</React.Fragment>
);
I modified the original code since I had to fetch data for the cards. Here is the modified version in two separate files (Event.tsx & Events.tsx): https://github.com/acm-uic/roll-call/tree/feature/printEvents/src/components
return (
<React.Fragment>
<CssBaseline />
<Container className={classes.cardGrid} maxWidth="md">
{/* End hero unit */}
<Grid container spacing={4}>
{cards.map(card => (
<Grid item key={card} xs={12} sm={6} md={4}>
<Card className={classes.card} raised>
<CardMedia
className={classes.cardMedia}
image="https://avatars3.githubusercontent.com/u/20177515?s=280&v=4"
title="Image title"
/>
<CardContent className={classes.cardContent}>
<Typography gutterBottom variant="h5" component="h2">
{summary ? summary : 'Busy'}
</Typography>
<Typography>
<div>
{start ? (start.dateTime ? start.dateTime : start.date) : <></>} | {end ? (end.dateTime ? end.dateTime : end.date) : <></>} | {location}
</div>
</Typography>
</CardContent>
<CardActions>
<Button size="small" color="primary">
View
</Button>
<Button size="small" color="primary">
Edit
</Button>
</CardActions>
</Card>
</Grid>
))}
</Grid>
</Container>
</React.Fragment>
);
You can use MUI's autolayout feature on the Grid to help you customize your card rendering.
import React from 'react';
import { Grid } from '#material-ui/core';
import CardData from 'path to get your data'; // Data must be an array
export default const Main = props => {
return (
<Grid container direction="row" justify="center" alignItems="center" spacing={3}>
{
CardData.map(data => (
<Grid item xs sm md lg key={data.key}>
<CustomCard data={data} />
</Grid>
))
}
</Grid>
);
}
By just providing the property xs, md, sm, lg and xl without the numbering, MUI will do the stacking for you as equally as possible within the same row. So all you need to do is adjusting the size of your card content to allow for several card placement within the same row.
I downloaded your repo and ran it on my machine. It only rendered AppBar so please let me know how to get the data to be displayed. However, I also looked at the code and I noticed one thing.
We are looping through the events and rendering component like so:
{(this.state.events && this.state.events.items)
? this.state.events.items.map((ev, key) =>
(<Event key={key} ev={ev} />)) //render material card for each event
: (<></>)}
But the <Container /> and <Grid /> components are being rendered from <Event /> component. It means that event cards will be contained in its own container and Grid. In my opinion, this is what could be causing the issue.
If we pull container and Grid out of Event.tsx and put in inside Events.tsx then it might fix it.
e.g.,
<Container>
<Grid ..>
this.state.events.items.map((ev, key) =>
(<Event key={key} ev={ev} />)) //render material card for each event
: (<></>)}
</Grid .. />
<Container />

Error when passing a functional component to a class component as a component prop

I create a functional component and a class component.
In the render method I want to call my functional component as a component prop.
My code:
function projectList(props) {
const { classes } = props
return (
<div>
{projects.slice(0, 5).map(project => (
<Card className={classes.card} key={project.id}>
<CardHeader
classes={{ title: classes.h6, subheader:
classes.subtitle1 }}
title={project.projectName}
subheader={project.h5}
/>
<CardActionArea>
<CardMedia
component="img"
alt={project.h5}
className={classes.media}
image={project.img}
/>
<CardContent>
<Typography paragraph>
{project.paragraph}
</Typography>
</CardContent>
</CardActionArea>
<CardActions className={props.classes.actions}>
<Button
className={props.classes.projectButton}
component={Link}
to={project.pathname}
size="medium"
color="secondary"
>
Project Details
</Button>
</CardActions>
</Card>
))}
</div>
)
}
projectList.propTypes = {
classes: PropTypes.any.isRequired, // eslint-disable-line
}
class Projects extends Component {
static propTypes = {
classes: PropTypes.any.isRequired, // eslint-disable-line
}
render() {
const { classes } = this.props
return (
<Grid container className={classes.projectPage}
direction="row">
<Grid item xs />
<Grid item>
<Grid container alignItems="center" direction="column">
{/* Title */}
<Grid item>
<Typography className={classes.h5} variant="h5">Latest
Projects</Typography>
</Grid>
<Grid item xs={12} sm={6} component={projectList} />
<Grid item className={classes.nextButton}>
<Button
className={classes.contained}
size="medium"
variant="contained"
onClick={this.handleShowMore}
>
See More
</Button>
</Grid>
</Grid>
</Grid>
<Grid item xs />
</Grid>
)
}
}
export default withStyles(styles)(Projects)
I have this error message appearing
index.js:1452 Warning: Failed prop type: The prop classes is marked as required in projectList, but its value is undefined.
Anyone could help me fix this ?
Not sure where that <Grid/> component comes from but you could pass an inline wrapper for projectLists and return it as a jsx element (you would need a capital first letter though):
<Grid item xs={12} sm={6} component={() => <ProjectList classes={classes} />} />
Don't forget to change the decleration to capital letter:
function ProjectList(props) {
...

React: If statements inside a map function

I'm struggling with this for a while now, I'm building a page so the user can create forms dynamically I have one react component that creates the forms and one that renders it, I'm currently facing problems with editing the forms already created.
const GigApplicationRenderer = (props) => {
const {
questions,
onSelectDelete,
onSelectEdit,
classes,
theme,
handleClickOpen,
handleClose,
open
} = props;
return (
<Fragment>
{questions.map((element, index) => (
<div className={classes.li} key={element.title}>
<Grid container spacing={24}>
<Grid item xs={12}>
{element.type === 'input' ? (
<Paper index={index} className={classes.paper}>
<Title
onSelectEdit={onSelectEdit}
onSelectDelete={onSelectDelete}
element={element}
handleClose={handleClose}
open={open}
/>
<TextField
className={classes.textField}
value=""
label="answer text"
margin="normal"
/>
</Paper>
) : element.type === 'radiobox' ? (
<Paper className={classes.paper}>
<Title
onSelectEdit={onSelectEdit}
onSelectDelete={onSelectDelete}
element={element}
handleClose={handleClose}
open={open}
/>
{element.options.map(option => (
<ListItem key={option} className={classes.itemsList}>
<RadioGroup>
<FormControlLabel
label={option}
value={option}
control={<Radio color="primary" />}
/>
</RadioGroup>
</ListItem>
))}
</Paper>
) : element.type === 'checkbox' ? (
<Paper className={classes.paper}>
<Title
onSelectEdit={onSelectEdit}
onSelectDelete={onSelectDelete}
element={element}
handleClose={handleClose}
open={open}
/>
{element.options.map(option => (
<ListItem key={option} className={classes.itemsList}>
<FormControlLabel
label={option}
value={option}
control={<Checkbox checked={false} color="primary" />}
/>
</ListItem>
))}
<Divider light />
</Paper>
) : null}
</Grid>
</Grid>
</div>
))}
</Fragment>
);
};
this is the component that renders the code, it has some if statements that check the properties of the forms created and renders it accordingly.
this is the title component:
const Title = (props) => {
const {
element, onSelectDelete, onSelectEdit, index, handleClose, open
} = props;
return (
<Grid container spacing={24}>
{console.log(element.title)}
<Grid item xs={12} sm={9}>
<Typography style={{ textAlign: 'left' }} variant="subheading" gutterBottom>
{element.title}
</Typography>
</Grid>
<Grid item xs={12} sm={3}>
<Tooltip enterDelay={100} leaveDelay={100} placement="bottom" title="Edit">
<IconButton onClick={onSelectEdit(element, index)} aria-label="Edit">
<EditIcon />
</IconButton>
</Tooltip>
<Tooltip enterDelay={100} leaveDelay={100} placement="bottom" title="Delete">
<IconButton aria-label="Delete">
<DeleteIcon onClick={onSelectDelete(element)} />
</IconButton>
</Tooltip>
</Grid>
<Dialog open={open} onClose={handleClose} aria-labelledby="form-dialog-title">
<DialogTitle id="form-dialog-title">
blabla
</DialogTitle>
<DialogContent>
<DialogContentText>
To subscribe to this website, please enter your email address here. We will send updates
occasionally.
</DialogContentText>
<TextField
autoFocus
// value={element.title}
margin="dense"
label="question title"
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="primary">
Cancel
</Button>
<Button onClick={handleClose} color="primary">
Save
</Button>
</DialogActions>
</Dialog>
</Grid>
);
};
I want it to open a dialog with the values of the element clicked so the user could edit it, the problem is that no matter which button was clicked, on the dialog, it always renders the last element of the form.
On the function onSelectEdit though, I get the correct element, I think it is happening because of the if statements of the first component.
the questions array look like this:
questions: [
{
title: 'Why do you want this job?',
type: 'input'
},
{
title: 'Do you know Javascript?',
type: 'radiobox',
options: ['yes', 'no']
},
{
title: 'What techs your know?',
type: 'checkbox',
options: ['html', 'css']
}
],
is there a way to render the correct element when the dialog opens?
I'm also open to any suggestion on how to accomplish this.

Categories

Resources