Parent action inside child component react - javascript

I am having two components, App and a panel. On button clcik, I add panel to the screen and all the actions corresponding actions inside of the panel is handled in the Panel component ( Actions are expand, collapse and close). Can I execute onClose method inside of the Panel component instead in App component. I am having a check of if cardBody is present in the parent component. For removing that card im setting its body to null inside App component. How can I do the same in Panel component.
https://codesandbox.io/s/basic-demo-card-6ywop7?file=/src/Panel.jsx:0-1022
import React, { useState } from "react";
import ReactDOM from "react-dom";
import Panel from "./Panel";
import "./styles.css";
function App() {
const [card, setCard] = useState({
cardId: "",
cardBody: null
});
const handleClick = (cardId, cardBody) => {
setCard({ cardId, cardBody });
};
const { cardId, cardBody } = card;
return (
<>
<div className="main">
<button onClick={() => handleClick("Panel 1", <h1>h1</h1>)}>
Add Panel 1
</button>
<button onClick={() => handleClick("Panel 2", <div>div</div>)}>
Add Panel 2
</button>
</div>
{cardBody && (
<div className="cards-container">
<Panel
key={cardId}
cardId={cardId}
cardBody={cardBody}
onClose={() =>
setCard({
cardId: "",
cardBody: null
})
}
/>
</div>
)}
</>
);
}
import React, { useState, useCallback } from "react";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import {
faSquareMinus,
faRectangleXmark
} from "#fortawesome/free-solid-svg-icons";
function Panel(props) {
const [isMinimized, setIsMinimized] = useState(false);
const { cardId, cardBody, onClose } = props;
const onMaximize = useCallback(() => {
setIsMinimized(!isMinimized);
}, [isMinimized]);
return (
<>
<div className={isMinimized ? "card-min" : "card"}>
<div className="card-actions">
<span onClick={onMaximize}>{cardId}</span>
{!isMinimized && (
<FontAwesomeIcon
icon={faSquareMinus}
onClick={() => {
setIsMinimized(true);
}}
/>
)}
<FontAwesomeIcon icon={faRectangleXmark} onClick={onClose} />
</div>
<div className="card-body">{cardBody}</div>
</div>
</>
);
}
export default Panel;

One workaround is to control the show/hide by display: 'none'/'block' inside the Panel component.
Panel component
import React, { useImperativeHandle, useState, useCallback } from
"react";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import {
faSquareMinus,
faRectangleXmark
} from "#fortawesome/free-solid-svg-icons";
function Panel(props) {
const [isMinimized, setIsMinimized] = useState(false);
const { cardId, cardBody, setCard } = props;
const onMaximize = useCallback(() => {
setIsMinimized(!isMinimized);
}, [isMinimized]);
return (
<>
<div
style={{ display: cardBody ? "block" : "none" }}
className={isMinimized ? "card-min" : "card"}
>
<div className="card-actions">
<span onClick={onMaximize}>{cardId}</span>
{!isMinimized && (
<FontAwesomeIcon
icon={faSquareMinus}
onClick={() => {
setIsMinimized(true);
}}
/>
)}
<FontAwesomeIcon
icon={faRectangleXmark}
onClick={() =>
setCard({
cardId: "",
cardBody: null
})
}
/>
</div>
<div className="card-body">{cardBody}</div>
</div>
</>
);
}
export default Panel;
App.js
import React, { useState, useRef } from "react";
import ReactDOM from "react-dom";
import Panel from "./Panel";
import "./styles.css";
function App() {
const [card, setCard] = useState({
cardId: "",
cardBody: null
});
const handleClick = (cardId, cardBody) => {
setCard({ cardId, cardBody });
};
const { cardId, cardBody } = card;
return (
<>
<div className="main">
<button onClick={() => handleClick("Panel 1", <h1>h1</h1>)}>
Add Panel 1
</button>
<button onClick={() => handleClick("Panel 2", <div>div</div>)}>
Add Panel 2
</button>
</div>
<div className="cards-container">
<Panel
key={cardId}
cardId={cardId}
cardBody={cardBody}
setCard={setCard}
/>
</div>
</>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
This is working example
Also, you can completely conditionally show and hide the inner content of the panel but you need some modifications in the style by moving the "card-min" and "card" class to an inner div instead of the root element on the component.

Related

Each child in a list should have a unique "key" prop Error [duplicate]

This question already has answers here:
Understanding unique keys for array children in React.js
(27 answers)
Closed 4 months ago.
Currently I am working on a project using React, Next.js and Ant-Design.
While working on my project, I got an error because I didn't use a unique key like this:
Below is the detailed error log.
Warning: Each child in a list should have a unique "key" prop.
Check the render method of `ForwardRef`. It was passed a child from BoardCard. See https://reactjs.org/link/warning-keys for more information.
at eval (webpack-internal:///./node_modules/antd/es/popover/index.js:30:31)
at eval (webpack-internal:///./node_modules/antd/es/card/Card.js:58:62)
at article
at BoardCard (webpack-internal:///./components/MyPage/BoardCard.js:34:19)
at li
at InternalItem (webpack-internal:///./node_modules/antd/es/list/Item.js:65:31)
at ul
at div
at div
at Spin (webpack-internal:///./node_modules/antd/es/spin/index.js:94:90)
at SpinFC (webpack-internal:///./node_modules/antd/es/spin/index.js:222:34)
at div
at List (webpack-internal:///./node_modules/antd/es/list/index.js:58:26)
at section
at BoardList (webpack-internal:///./components/MyPage/BoardList.js:22:78)
at section
at MyBoard
at section
at MyInfo
at header
at O (webpack-internal:///./node_modules/styled-components/dist/styled-components.browser.esm.js:31:19811)
at AppLayout (webpack-internal:///./components/AppLayout/index.js:28:23)
at profile
at App (webpack-internal:///./pages/_app.js:28:24)
at Provider (webpack-internal:///./node_modules/react-redux/es/components/Provider.js:13:3)
at Wrapper (webpack-internal:///./node_modules/next-redux-wrapper/es6/index.js:184:35)
at ErrorBoundary (webpack-internal:///./node_modules/next/dist/compiled/#next/react-dev-overlay/client.js:8:20746)
at ReactDevOverlay (webpack-internal:///./node_modules/next/dist/compiled/#next/react-dev-overlay/client.js:8:23395)
at Container (webpack-internal:///./node_modules/next/dist/client/index.js:241:5)
at AppContainer (webpack-internal:///./node_modules/next/dist/client/index.js:833:24)
at Root (webpack-internal:///./node_modules/next/dist/client/index.js:986:26)
As a result of checking the error log, it was confirmed that the error occurred in the Boardlist and BoardCard components.
So I checked the key of the relevant component, but I am using a unique key.
import React from 'react';
import { useSelector } from 'react-redux';
import { List } from 'antd';
import BoardCard from './BoardCard';
const BoardList = () => {
const { boardPosts } = useSelector((state) => state.user);
return (
<section>
<List
itemLayout="vertical"
bordered
size="large"
pagination={{
onChange: (page) => console.log(page), pageSize: 3,
}}
dataSource={boardPosts}
renderItem={(item) => (
<List.Item>
<BoardCard post={item} key={item.id}/>
</List.Item>
)}
/>
</section>
)
};
export default BoardList;
import React, { useState, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Card, Modal, Button, Popover, Row, Col, message } from 'antd';
import PropTypes from 'prop-types';
import PostModal from '../Modal/PostModal';
import PostDeleteModal from '../HomePost/PostDeleteModal';
import {
likePostRequestAction, unLikePostRequestAction,
moveToCommentRequestAction, returnToCommentRequestAction
} from '../../reducers/post';
import {
BoardCardHeader, BoardCardBody, MoreIcon, ColWrapper, CardTextWrapper,
CardTitle, CardText, CardContent, HeaderBtn, TwoToneHeartBtnIcon,
HeartBtnIcon, CommentBtnIcon, CardImageWrapper, ImageWrapper
} from './styles';
const BoardCard = ({ post }) => {
const dispatch = useDispatch();
const [visible, setVisible] = useState(false);
const id = useSelector((state) => state.user.me.id);
const liked = post.Likers.find((v) => v.id === id);
const onLikePost = useCallback(() => {
dispatch(likePostRequestAction(post.id));
}, []);
const unLikePost = useCallback(() => {
dispatch(unLikePostRequestAction(post.id));
}, []);
const showPostModal = useCallback(() => {
setVisible(true);
}, []);
const boardCardCommentBtn = useCallback(() => {
setVisible(true);
dispatch(moveToCommentRequestAction());
}, []);
const boardmodalOkBtn = useCallback(() => {
setVisible(false);
dispatch(returnToCommentRequestAction());
}, []);
const boardmodalCancelBtn = useCallback(() => {
setVisible(false);
dispatch(returnToCommentRequestAction());
}, []);
return (
<article>
<Card
headStyle={BoardCardHeader}
bodyStyle={BoardCardBody}
hoverable
extra={[
<Popover
trigger="click"
content={
<>
<Button>Modify</Button>
<PostDeleteModal post={post} />
</>
}
>
<MoreIcon key="ellipsis"/>
</Popover>
]}
>
<Row>
<ColWrapper xs={24} md={16}>
<CardTextWrapper>
<CardText
title={<CardTitle>{post.title}</CardTitle>}
description={post.desc}
onClick={showPostModal}
/>
<CardContent onClick={showPostModal}>{post.recipes}</CardContent>
</CardTextWrapper>
<div>
{
liked
? <HeaderBtn type='text' icon={<TwoToneHeartBtnIcon twoToneColor="#eb2f96" onClick={unLikePost} />}>{post.Likers.length}</HeaderBtn>
: <HeaderBtn type='text' icon={<HeartBtnIcon />} onClick={onLikePost}>{post.Likers.length}</HeaderBtn>
}
<HeaderBtn type='text' icon={<CommentBtnIcon />} onClick={boardCardCommentBtn} >{post.Comments.length}</HeaderBtn>
</div>
</ColWrapper>
<Col xs={24} md={8}>
<CardImageWrapper>
<ImageWrapper
alt="board image"
src={`http://localhost:3065/${post.Images[0]?.src}`}
onClick={showPostModal}
/>
</CardImageWrapper>
</Col>
</Row>
</Card>
<Modal
centered
visible={visible}
onOk={boardmodalOkBtn}
onCancel={boardmodalCancelBtn}
width={1000}
>
<PostModal post={post} />
</Modal>
</article>
);
};
BoardCard.propTypes = {
post: PropTypes.shape({
id: PropTypes.number,
User: PropTypes.object,
title: PropTypes.string,
desc: PropTypes.string,
content: PropTypes.arrayOf(PropTypes.object),
Images: PropTypes.arrayOf(PropTypes.object),
tag: PropTypes.string,
Comments: PropTypes.arrayOf(PropTypes.object),
})
};
export default BoardCard;
I tried to solve the problem, but couldn't find a way.
So, I would like to know why the above problem occurs and how to solve it.
You must put the key on the first child
const BoardList = () => {
const { boardPosts } = useSelector((state) => state.user);
return (
<section>
<List
itemLayout="vertical"
bordered
size="large"
pagination={{
onChange: (page) => console.log(page), pageSize: 3,
}}
dataSource={boardPosts}
renderItem={(item) => (
<List.Item key={item.id}>
<BoardCard post={item}/>
</List.Item>
)}
/>
</section>
)
};

Execute child component action in the parent using react

I am having two components, App and a panel. On button clcik, I add panel to the screen and all the actions corresponding actions inside of the panel is handled in the Panel component ( Actions are expand, collapse and close). Can I somehow execute the same actions inside of the app component using useImperativeHandle hook using ref's. Also can I execute onClose method inside of the Panel component, here i am actually as a callback.
https://codesandbox.io/s/basic-demo-card-6ywop7?file=/src/Panel.jsx:0-985
Can someone help me here
App
import React, { useState, useRef } from "react";
import ReactDOM from "react-dom";
import Panel from "./Panel";
import "./styles.css";
function App() {
const [card, setCard] = useState({
cardId: "",
cardBody: null
});
const ref = useRef();
const handleClick = (cardId, cardBody) => {
setCard({ cardId, cardBody });
};
const { cardId, cardBody } = card;
return (
<>
<div className="main">
<button onClick={() => ref?.current?.expandBtn()}>Open from out</button>
<button onClick={() => handleClick("Panel 1", <h1>h1</h1>)}>
Add Panel 1
</button>
<button onClick={() => handleClick("Panel 2", <div>div</div>)}>
Add Panel 2
</button>
</div>
{cardBody && (
<div className="cards-container">
<Panel
key={cardId}
cardId={cardId}
cardBody={cardBody}
onClose={() =>
setCard({
cardId: "",
cardBody: null
})
}
/>
</div>
)}
</>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Panel
import React, { useImperativeHandle, useState, useRef } from "react";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import {
faSquareMinus,
faRectangleXmark
} from "#fortawesome/free-solid-svg-icons";
export default function Panel(props) {
const [isMinimized, setIsMinimized] = useState(false);
const { cardId, cardBody, onClose, ref } = props;
const expandRef = useRef();
useImperativeHandle(ref, () => {
return {
expandBtn: () => expandRef.current.onMaximize()
};
});
const onMaximize = () => {
setIsMinimized(!isMinimized);
};
return (
<>
<div className={isMinimized ? "card-min" : "card"}>
<div className="card-actions">
<span onClick={onMaximize}>{cardId}</span>
{!isMinimized && (
<FontAwesomeIcon
icon={faSquareMinus}
onClick={() => {
setIsMinimized(true);
}}
/>
)}
<FontAwesomeIcon icon={faRectangleXmark} onClick={onClose} />
</div>
<div className="card-body">{cardBody}</div>
</div>
</>
);
}
Yes, you can the child's function from the Parent using useImperativeHandle. What your implementation is missing is forwardRef. passing ref as props won't work. What you have to do is forward the ref from child to parent.
const Panel = React.forwardRef(function (props, ref) {
const [isMinimized, setIsMinimized] = useState(false);
const { cardId, cardBody, onClose } = props;
const onMaximize = () => {
setIsMinimized(!isMinimized);
};
useImperativeHandle(ref, () => {
return {
expandBtn: onMaximize
};
});
return (
<>
<div className={isMinimized ? "card-min" : "card"}>
<div className="card-actions">
<span onClick={onMaximize}>{cardId}</span>
{!isMinimized && (
<FontAwesomeIcon
icon={faSquareMinus}
onClick={() => {
setIsMinimized(true);
}}
/>
)}
<FontAwesomeIcon icon={faRectangleXmark} onClick={onClose} />
</div>
<div className="card-body">{cardBody}</div>
</div>
</>
);
})
export default Panel;
Pass the ref from the App
function App() {
const [card, setCard] = useState({
cardId: "",
cardBody: null
});
const ref = useRef();
const handleClick = (cardId, cardBody) => {
setCard({ cardId, cardBody });
};
const { cardId, cardBody } = card;
return (
<>
<div className="main">
<button onClick={() => ref?.current?.expandBtn()}>Open from
out</button>
<button onClick={() => handleClick("Panel 1", <h1>h1</h1>)}>
Add Panel 1
</button>
<button onClick={() => handleClick("Panel 2", <div>div</div>)}>
Add Panel 2
</button>
</div>
{cardBody && (
<div className="cards-container">
<Panel
ref={ref}
key={cardId}
cardId={cardId}
cardBody={cardBody}
onClose={() =>
setCard({
cardId: "",
cardBody: null
})
}
/>
</div>
)}
</>
);
}
This might help https://blogsbyarjun.hashnode.dev/how-to-update-childs-state-from-parent-in-react-1

get data from child components to parents components in react js

I want to get value from child components to parent components.
Here is my code.
//this is child component
import { React } from "react";
const Tab = () => {
const changeTab = (index) => {
console.log(index);
};
return (
<>
<div className="flex gap-10">
<button
onClick={() => changeTab(1)}
className="bg-gray-700 p-2 text-white"
>
btn1
</button>
</div>
</>
);
};
export default Tab;
//this is parent component
import React from "react";
import Nav1 from "./Components/Navbar/Nav1";
import Tab from "./Tab";
const App = () => {
return (
<>
<Tab />
<div>
<Nav1 />
</div>
</>
);
};
export default App;
I want to log the value of the index in a parent component that was coming from a child.
define changeTab in parent component and pass it through props to Tab.
parent:
import React from "react";
import Nav1 from "./Components/Navbar/Nav1";
import Tab from "./Tab";
const App = () => {
const changeTab = (index) => {
console.log(index);
};
return (
<>
<Tab changeTab={changeTab}/>
<div>
<Nav1 />
</div>
</>
);
};
export default App;
and child component:
import { React } from "react";
const Tab = ({changeTab}) => {
const onChangeTab = (index) => {
changeTab(index);
// other stuff
};
return (
<>
<div className="flex gap-10">
<button
onClick={() => onChangeTab(1)}
className="bg-gray-700 p-2 text-white"
>
btn1
</button>
</div>
</>
);
};
export default Tab;
You can use context API:
https://reactjs.org/docs/context.html
Or you can transfer changeTab function to parent component and pas it as prop
Your problem is common(with most people). And the solution is to lift the state up(React docs).
Which basically means, you'll have to maintain the state in the parent component and pass the value and method to the child component.
// App.jsx
import React from "react";
import Nav1 from "./Components/Navbar/Nav1";
import Tab from "./Tab";
const App = () => {
const changeTab = (index) => {
console.log(index);
};
return (
<>
<Tab handleTabChange={changeTab}/>
<div>
<Nav1 />
</div>
</>
);
};
export default App;
import { React } from "react";
const Tab = (props) => {
const changeTab = (index) => {
props.handleTabChange(index);
};
return (
<>
<div className="flex gap-10">
<button
onClick={() => changeTab(1)}
className="bg-gray-700 p-2 text-white"
>
btn1
</button>
</div>
</>
);
};
export default Tab;

Add items to Cart using React Context

I am new with React, I am trying to do the cart of the app that i am doing and I am having problems sending the items to the cart avoiding to have them duplicate or adding another extra item in the cart. These is the CartProvider code:
import { useState } from "react";
import CartContext from "./CartContext";
export const CartProvider = ({ children }) => {
const [list, setList] = useState();
const addCart = (varietals, quantity) => {
if (isInCart(varietals.item.id ) === -1){
setList(varietals)
}else{
list[isInCart].quantity += quantity
}
};
const isInCart = (id) => {
return list.findIndex(varietals => varietals.id === id)
};
return(
<>
<CartContext.Provider value={{list, addCart}}>
{children}
</CartContext.Provider>
</>);
};
This is the ItemDetail code which i use to display the Item:
import { useContext, useState } from "react";
import { Button, Container } from "react-bootstrap";
import { Link } from "react-router-dom";
import CartContext from "../../Context/CartContext";
import Item from "../Item/Item";
import ItemCountComponent from "../ItemCount";
const ItemDetail = ({ varietals }) => {
const [checkout, setCheckout] = useState(false);
const { list, addCart } = useContext(CartContext);
const onAdd = (count) => {
console.log("Selected ", count);
setCheckout(true);
addCart({Item: varietals, Quantity: count});
};
console.log(list)
return (
<>
<br />
<Container className="py-5 px-5 shadow">
<Item varietals={varietals} />
<div className="ml-4 mr-3">
<div className="font-italic mb-4 text-center text-muted">{varietals.description}</div>
{checkout ? <Link to='/Cart'><Button variant="info">Checkout</Button></Link> : <ItemCountComponent className="d-flex justify-content-center" onAdd={onAdd} stock={5} initial={1} />}
</div>
</Container>
</>
)
};
export default ItemDetail;
This is the Item.jsx:
import { Card, Container } from "react-bootstrap";
import "./Style.scss";
const Item = ({ varietals }) => {
return (
<>
<Container className="px-1">
<Card className="clemmy">
<Card.Img variant="top" src={varietals.pictureUrl} className="shadow"/>
<Card.Body>
<Card.Title className="d-flex justify-content-center text-muted">
{varietals.title}
</Card.Title>
<Card.Subtitle className="d-flex justify-content-center text-muted">
${varietals.price}
</Card.Subtitle>
</Card.Body>
</Card>
</Container>
</>
)
};
export default Item;
This is the ItemListContainer.jsx:
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import aimara from "../../aimara";
import ItemList from "../../Components/ItemList/ItemList";
const ItemListContainer = () => {
const [varietals, setVarietals] = useState([])
const { categoryId } = useParams();
useEffect(() => {
const myPromise = new Promise((resolve, reject) => {
if (categoryId) {
const products = aimara.filter((producto) => {
return producto.category.toString() === categoryId;
});
resolve(products);
} else resolve(aimara);
});
myPromise.then((result) => setVarietals(result));
}, [categoryId]);
return <ItemList varietals={varietals} />
};
export default ItemListContainer;
The error that I am seeing is "TypeError: Cannot read property 'id' of undefined"
If there is someone that could help me would be much appreciate it. Also, in case you need some extra file let me know and I update the post as quickly as I can. Cheers

Call function from material ui fonction

I want to pass a function as a props to my material ui function.
The given function is undefined in my material ui fonction.
import React, { Component } from 'react';
import styled from 'styled-components';
import InputBase from '#material-ui/core/InputBase';
import IconButton from '#material-ui/core/IconButton';
import Menu from '#material-ui/core/Menu';
import MenuItem from '#material-ui/core/MenuItem';
import SearchIcon from '#material-ui/icons/Search';
import Avatar from '#material-ui/core/Avatar';
import '../../css/App.css';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { withTranslation } from 'react-i18next';
import CreateNewGarden from './CreateNewGarden';
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
};
this.myFunction = this.myFunction.bind(this);
}
myFunction() {
console.log("OK")
}
render() {
return (
<div>
<CreateNewGarden myFunction={this.myFunction}/>
</div>
);
}
}
const mapStateToProps = (state) => ({
});
Dashboard.propTypes = {
};
export default withTranslation()(withRouter(connect(mapStateToProps)(Dashboard)));
I send CreateNewGarden myFunction={this.myFunction} as a props and in my others file.
I have:
import React from 'react';
import { withStyles } from '#material-ui/core/styles';
import Dialog from '#material-ui/core/Dialog';
import MuiDialogTitle from '#material-ui/core/DialogTitle';
import MuiDialogContent from '#material-ui/core/DialogContent';
import MuiDialogActions from '#material-ui/core/DialogActions';
import IconButton from '#material-ui/core/IconButton';
import CloseIcon from '#material-ui/icons/Close';
import Typography from '#material-ui/core/Typography';
import Slider from '#material-ui/core/Slider';
import { useTranslation } from 'react-i18next';
import measureLogo from '../../assets/images/measure.png';
import { Button } from '../../components';
const styles = (theme) => ({
root: {
margin: 0,
padding: theme.spacing(2),
},
closeButton: {
position: 'absolute',
right: theme.spacing(1),
top: theme.spacing(1),
color: theme.palette.grey[500],
}
});
const DialogTitle = withStyles(styles)((props) => {
const {
children, classes, onClose, ...other
} = props;
return (
<MuiDialogTitle disableTypography className={classes.root} {...other}>
<Typography variant="h6">{children}</Typography>
{onClose ? (
<IconButton aria-label="close" className={classes.closeButton} onClick={onClose}>
<CloseIcon />
</IconButton>
) : null}
</MuiDialogTitle>
);
});
const DialogContent = withStyles((theme) => ({
root: {
padding: theme.spacing(2)
}
}))(MuiDialogContent);
const DialogActions = withStyles((theme) => ({
root: {
margin: 0,
padding: theme.spacing(1)
}
}))(MuiDialogActions);
export default function CustomizedDialogs(props) {
const [open, setOpen] = React.useState(false);
// eslint-disable-next-line no-unused-vars
const [height, setHeight] = React.useState(0);
// eslint-disable-next-line no-unused-vars
const [width, setWidth] = React.useState(0);
console.log("ici = " + props.myFunction)
const setSizeHeight = () => (e, value) => {
setHeight(value);
};
const setSizeWidth = () => (e, value) => {
setWidth(value);
};
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
const { t } = useTranslation();
return (
<div className="marginCardComponent">
<Button
onClick={handleClickOpen}
text="dashboard.createGardenBtn"
type="submit"
/>
<Dialog onClose={handleClose} aria-labelledby="customized-dialog-title" open={open}>
<DialogTitle id="customized-dialog-title" className="centerText" onClose={handleClose}>
{t('dashboard.createGardenTitle')}
</DialogTitle>
<DialogContent className="logoMeasureParent">
<img src={measureLogo} alt="Logo" className="logoMeasure centerText" />
</DialogContent>
<DialogContent dividers>
<Typography className="centerText" gutterBottom>
{ t('dashboard.createGardenDetail') }
</Typography>
</DialogContent>
<div className="marginLeft3">
<p>{ t('dashboard.height') }</p>
</div>
<div className="centerSlider">
<Slider
/* eslint-disable-next-line react/destructuring-assignment */
defaultValue={0}
aria-labelledby="discrete-slider"
valueLabelDisplay="auto"
step={1}
marks
min={1}
max={20}
onChange={setSizeHeight()}
/>
</div>
<div className="marginLeft3">
<p>{ t('dashboard.width') }</p>
</div>
<div className="centerSlider">
<Slider
/* eslint-disable-next-line react/destructuring-assignment */
defaultValue={0}
aria-labelledby="discrete-slider"
valueLabelDisplay="auto"
step={1}
marks
min={1}
max={20}
onChange={setSizeWidth()}
/>
</div>
<DialogActions>
<Button
onClick={handleClose}
text="dashboard.cancelBtn"
type="submit"
/>
<Button
onClick={props.myFunction}
text="dashboard.createGardenBtn"
type="submit"
/>
</DialogActions>
</Dialog>
</div>
);
}
When i click on the button it does nothing and when i print myFunction it tell me undefined.
Why i can't give a props to the function and call myFunction ?
Thank you for your help.
You need to call it outside of onClick. Do it like this:
const handleClick = (e) => {
e.preventDefault()
props.myFunction()
}
And in the button:
<Button
onClick={handleClick}
text="dashboard.createGardenBtn"
type="submit"
/>
That will work. It just isnt letting you call it inside onClick
You can also just do this:
<Button
onClick={() => props.myFunction()}
text="dashboard.createGardenBtn"
type="submit"
/>

Categories

Resources