props.children not rendering when using React and Material UI - javascript

props.children is not working in my parent component, BoxCard. When I reference the child component directly instead of props.children, it works. Here's the code that's not working:
// AddUserForm.js
function AddUserForm(props) {
function handleSubmit(event) {
event.preventDefault();
}
return (
<BoxCard>
<Box component="form" onSubmit={handleSubmit}>
<TextField required id="name" label="Name" variant="filled" />
<TextField required type="number" id="age" label="Age" variant="filled" InputLabelProps={{ shrink: true }} InputProps={{inputProps: { min: 0, step: 1 }}}/>
<Button type="submit" variant="contained" startIcon={<FontAwesomeIcon icon={solid('circle-plus')}/>}>Add User</Button>
</Box>
</BoxCard>
)
}
export default AddUserForm;
// BoxCard.js
function BoxCard(props) {
return (
<Box sx={{ minWidth: 275 }}>
<Card variant="outlined">
<CardContent>
{props.children}
</CardContent>
</Card>
</Box>
)
}
export default BoxCard;

Related

how to show data fetched from api in select mui

I'm trying to show the data, I fetched from Api in select menu. but there seems to be a issue. I'm getting the data, but it's not showing in the select menu. it just shows empty. but I can get the mapped data in console. it just not showing in the select component.
help me figure out. thanks in advance :)
here's my code
export function TransferRBTCard(props) {
const [TransferData, setTransferData] = useState([])
const [ContactValue, setContactValue] = useState('')
const handleChange = (event) => {
setContactValue(event.target.value);
};
const TokenData = () => {
axios.get('http://localhost:8006/api/v2/get/list').then(function (res) {
try {
var result = res.data.data;
console.log(result)
setTransferData(result)
}
catch (error) {
console.log(error)
}
})
}
useEffect(() => {
TokenData()
}, [])]
const handleSubmit = (evnt,) => {
evnt.preventDefault();
axios.post('http://localhost:8006/api/v2/add/transfer')
.then(response => {
if (response.data.success === true) {
alert(response.data.message)
}
})
.catch(error => {
console.log(error.message)
});
}
return (
<Card {...props}>
<CardContent>
<Stack direction="row" alignItems="center" gap={1}>
<ShareOutlinedIcon sx={{ color: "text.secondary" }} />
<Typography sx={{ fontSize: 16, fontWeight: 'bold' }} color="text.secondary" gutterBottom>
Transfer RBT
</Typography>
</Stack>
<Grid>
<FormControl size="small" fullWidth >
<Stack flexDirection='column' gap={1.5} mt={1}>
<InputLabel id="Contact Select" sx={{ mt: 1 }}>Select Contact</InputLabel>
<Select
labelId="Contact Select"
id="demo-simple-select"
value={ContactValue}
label='Select Contact'
onChange={handleChange}
>
{TransferData.map((data) => {
<MenuItem key={data.id} value={data.id}>{data.name}</MenuItem>
})}
</Select>
<TextField
id="filled-hidden-label-small"
label="Receiver" variant="outlined" size="small"
onChange={handleChange}
value={TransferData}
name="Receiver"
inputProps={
{ readOnly: true, }}
className="form-control"
/>
<TextField
id="filled-hidden-label-small" type='number'
label="Amount" variant="outlined" size="small"
onChange={handleChange}
name="Amount"
className="form-control"
/>
<TextField
id="filled-hidden-label-small"
label="Comments" variant="outlined"
multiline
rows={2}
onChange={handleChange}
name="Comments"
className="form-control"
/>
<Button
variant="contained"
type="submit"
onClick={handleSubmit}
sx={{ alignSelf: 'center', backgroundColor: '#000073' }} >Submit</Button>
</Stack>
</FormControl>
</Grid>
</CardContent>
</Card>
);
}
You are not returning from the map function (more correctly, you return undefined by not stating a return).
Change this:
{TransferData.map((data) => {
<MenuItem key={data.id} value={data.id}>{data.name}</MenuItem>
})}
to this:
{TransferData.map((data) => (
<MenuItem key={data.id} value={data.id}>{data.name}</MenuItem>
))}
Note that it is the same as writing:
{TransferData.map((data) => {
return <MenuItem key={data.id} value={data.id}>{data.name}</MenuItem>
})}

Formik Warning: Maximum update depth exceeded

I am working on EDIT formik form, this form is in form of MODAL. when setState is passed as setState(true) than form will appear. But the problem is that without clicking onClick setState is being triggerd (according to error). In form values are already passed as it is EDIT form. I changed onClick={editStory} to onClick={()=> editStory()} still error not gone
Error: "Warning: Maximum update depth exceeded. This can happen when a
component calls setState inside useEffect, but useEffect either
doesn't have a dependency array, or one of the dependencies changes on
every render.
at EditQs (webpack-internal:///./src/new-components/Projects/EditQs.js:106:23)"
MyQs2.js
function MyQs2({row, isItemSelected, labelId, index}) {
const theme = useTheme();
const editStory = () => {
console.log('editstory is triggering')
setOpenStoryDrawer(true);
};
const [openStoryDrawer, setOpenStoryDrawer] = React.useState(false);
const handleStoryDrawerOpen = () => {
setOpenStoryDrawer(false);
};
const [allUsers, setAllUsers] = React.useState([])
const [allUsersObj, setAllUsersObj] = React.useState([])
const [allProjects, setAllProjects] = React.useState([])
//Error occur in this useEffect but i need updated data to show from firestore
React.
useEffect(() => {
readAllUsers()
readAllProjects()
}, [])
const readAllUsers = async()=> {
console.log('readAllUsesrs is calling')
try{
firebase.firestore().collection("users").where("role", "==", 'user')
.onSnapshot(function (val) {
let user = []
val.forEach(function(doc) {
user.push(doc.data().name);
setAllUsers(user)
})})
}
const readAllProjects = async() => {
console.log('readAllUsesrs is calling')
const snapshot = await firebase.firestore().collection('projects').get()
setAllProjects( snapshot.docs.map(doc => doc.data().name) );
}
return (
<>
<TableRow hover role="checkbox" aria-checked={isItemSelected} tabIndex={-1} key={index} selected={isItemSelected}>
<TableCell padding="checkbox" sx={{ pl: 3 }} onClick={(event) => handleClick(event, row.question)}>
<Checkbox
color="primary"
checked={isItemSelected}
inputProps={{
'aria-labelledby': labelId
}}
/>
</TableCell>
<TableCell
component="th"
id={labelId}
scope="row"
onClick={(event) => handleClick(event, row.projects)}
sx={{ cursor: 'pointer' }}
>
<Typography variant="subtitle1" sx={{ color: theme.palette.mode === 'dark' ? 'grey.600' : 'grey.900' }}>
{' '}
{row.question}{' '}
</Typography>
<Typography variant="caption"> {row.projects} </Typography>
</TableCell>
<TableCell>{row.projects}</TableCell>
<TableCell align="right">{row.assignTo}</TableCell>
<TableCell align="center">{row.priority}</TableCell>
<TableCell align="center">
{row.state === "published" && <Chip label="published" size="small" chipcolor="success" />}
{row.state === "unpublished" && <Chip label="unpublished" size="small" chipcolor="orange" />}
{row.state === 'Active' && <Chip label="Confirm" size="small" chipcolor="primary" />}
</TableCell>
<TableCell align="center" sx={{ pr: 3 }}>
<IconButton color="primary" size="large">
<VisibilityTwoToneIcon sx={{ fontSize: '1.3rem' }} />
</IconButton>
//below onClick is triggering
<IconButton color="secondary" size="large" onClick={()=> editStory()}
<EditTwoToneIcon sx={{ fontSize: '1.3rem' }} />
</IconButton>
</TableCell>
</TableRow>
// This calls a EditPage
<EditQs existingQs={row} open={openStoryDrawer} handleDrawerOpen={handleStoryDrawerOpen} allProjects={allProjects} allUsers={allUsers} />
</>
);
}
export default MyQs2
According to error appears in this Form page
EditQs.js
const EditQs = ({ open, handleDrawerOpen, existingQs, allProjects, allUsers }) => {
const dispatch = useDispatch();
const sendDataToFirestore = (item) => {
try{
firebase.firestore()
.collection('projects')
.doc(item.projects)
.update({
question : firebase.firestore.FieldValue.arrayUnion(item)
}).then(
dispatch(
openSnackbar({
open: true,
message: 'New Question added',
variant: 'alert',
alert: {
color: 'success'
},
close: false
})
)
)
}catch(err){
console.log('an error occured', err)
}
}
const formik = useFormik({
enableReinitialize: true, //if i remove this, error gone but this is responsible
for adding values in formik during render
validateOnChange:false,
validateOnBlur:false,
initialValues: {
id: existingQs.id ? existingQs.id : '',
question: existingQs.question? existingQs.question : '',
projects: existingQs.projects? existingQs.projects : '',
assignTo: existingQs.assignTo ? existingQs.assignTo : '',
priority: existingQs.priority ? existingQs.priority : '',
dueDate: existingQs.dueDate ? new Date(existingQs.dueDate) : new Date(),
state: existingQs.state ? existingQs.state : '',
image: existingQs.image
},
validationSchema,
onSubmit: (values,{resetForm}) => {
const item = {
id: values.id,
question: values.question,
projects: values.projects,
assignTo: values.assignTo,
priority: values.priority,
dueDate: values.dueDate ? new Date(values.dueDate) : new Date(),
state: values.state,
image: values.image
};
sendDataToFirestore(item);
() => handleDrawerOpen();
resetForm()
readAllProjects()
}
});
return (
<Drawer
sx={{
ml: open ? 3 : 0,
flexShrink: 0,
zIndex: 1200,
overflowX: 'hidden',
width: { xs: 320, md: 450 },
'& .MuiDrawer-paper': {
height: '100vh',
width: { xs: 320, md: 450 },
position: 'fixed',
border: 'none',
borderRadius: '0px'
}
}}
variant="temporary"
anchor="right"
open={open}
ModalProps={{ keepMounted: true }}
onClose={() => handleDrawerOpen}
>
{open && (
<Box sx={{ p: 3 }}>
<form onSubmit={formik.handleSubmit}>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<Grid container spacing={3}>
<Grid item xs={12}>
<Typography variant="h4">Edit Question</Typography>
</Grid>
<Grid item xs={12}>
<Grid container alignItems="center" spacing={2}>
<Grid item xs={12} sm={4}>
<Typography variant="subtitle1">Question:</Typography>
</Grid>
<Grid item xs={12} sm={8}>
<TextField
fullWidth
id="question"
name="question"
multiline
rows={3}
value={formik.values.question}
onChange={formik.handleChange}
error={formik.touched.question && Boolean(formik.errors.question)}
helperText={formik.touched.question && formik.errors.question}
/>
</Grid>
</Grid>
</Grid>
<Grid item xs={12}>
<Grid container alignItems="center" spacing={2}>
<Grid item xs={12} sm={4}>
<Typography variant="subtitle1">Assign to:</Typography>
</Grid>
<Grid item xs={12} sm={8}>
<FormControl fullWidth sx={{ m: 1 }}>
<InputLabel>Choose a user</InputLabel>
<Select
id="assignTo"
name="assignTo"
displayEmpty
value={formik.values.assignTo}
onChange={formik.handleChange}
label='Assign to'
inputProps={{ 'aria-label': 'assignTo' }}
>
{allUsers.map((val, index) => (
<MenuItem key={index} value={val}>
{val}
</MenuItem>
))}
</Select>
</FormControl>
</Grid>
</Grid>
</Grid>
<Grid item xs={12}>
<Grid container alignItems="center" spacing={2}>
<Grid item xs={12} sm={4}>
<Typography variant="subtitle1">project:</Typography>
</Grid>
<Grid item xs={12} sm={8}>
<FormControl fullWidth sx={{ m: 1 }}>
<InputLabel>Choose a Project</InputLabel>
<Select
id="projects"
name="projects"
displayEmpty
value={formik.values.projects}
onChange={formik.handleChange}
label='projects'
inputProps={{ 'aria-label': 'projects' }}
>
{allProjects.map((val, index) => (
<MenuItem key={index} value={val}>
{val}
</MenuItem>
))}
</Select>
</FormControl>
</Grid>
</Grid>
</Grid>
<Grid item xs={12}>
<Grid container alignItems="center" spacing={2}>
<Grid item xs={12} sm={4}>
<Typography variant="subtitle1">Prioritize:</Typography>
</Grid>
<Grid item xs={12} sm={8}>
<FormControl>
<RadioGroup
row
aria-label="color"
value={formik.values.priority}
onChange={formik.handleChange}
name="priority"
id="priority"
>
<FormControlLabel value="low" control={<Radio color="primary" sx={{ color: 'primary.main' }} />} label="Low" />
<FormControlLabel
value="medium"
control={<Radio color="warning" sx={{ color: 'warning.main' }} />}
label="Medium"
/>
<FormControlLabel value="high" control={<Radio color="error" sx={{ color: 'error.main' }} />} label="High" />
</RadioGroup>
</FormControl>
</Grid>
</Grid>
</Grid>
<Grid item xs={12}>
<Grid container alignItems="center" spacing={2}>
<Grid item xs={12} sm={4}>
<Typography variant="subtitle1">State:</Typography>
</Grid>
<Grid item xs={12} sm={8}>
<FormControl fullWidth sx={{ m: 1 }}>
<InputLabel >State of question</InputLabel>
<Select
id="state"
name="state"
displayEmpty
value={formik.values.state}
onChange={formik.handleChange}
// label='choose question state'
inputProps={{ 'aria-label': 'choose question state' }}
>
{states.map((val, index) => (
<MenuItem key={index} value={val.title}>
{val.title}
</MenuItem>
))}
</Select>
</FormControl>
</Grid>
</Grid>
</Grid>
<Grid item xs={12}>
<AnimateButton>
<Button fullWidth variant="contained" type="submit">
Save
</Button>
</AnimateButton>
</Grid>
</Grid>
</LocalizationProvider>
</form>
</Box>
)}
</Drawer>
);
};
export default EditQs;
First issue is setAllUsers(readAllUsers()). You are calling setAllUsers passing a function readAllUsers as argument but inside this function you are calling setAllUsers again
.onSnapshot(function (val) {
let user = []
val.forEach(function(doc) {
user.push(doc.data().name);
// setAllUsers again
setAllUsers(user)
})})
Every time you change the state, your component is getting rerendered.
It would be better to write different useEffect for each state setup. Each useEffect will have different dependentcies. Setting correct depencencies needs analysing the code. Otherwise you might not get correct state or your component might keep rerendering

Form is not submitting in react js

I have a form that should print the data in console but unfortunately I'm not able to.
I want to print data to the console when a form is submitted.
The form is not submitting don't know why. I have the code below.
I would be very grateful if you could decide.
import { Button, Grid, Paper, TextField } from "#mui/material";
import React from "react";
import { useForm } from "react-hook-form";
export default function Page2(props) {
const { handleSubmit } = useForm();
const handelInputChange = (e) => {
const { name, value } = e.target;
console.log(name, value);
};
const handleData = (data) => {
console.log("data");
};
return (
<>
<Paper
style={{ margin: "10px auto", textAlign: "center" }}
elevation={24} >
<h1 style={{ textAlign: "center" }}>Todo Application</h1>
<form onSubmit={handleSubmit(handleData)}>
<Grid
style={{ margin: "10px" }}
container
spacing={1}
direction="column" >
<Grid item xs={6}>
<TextField
name="title"
label="Title"
variant="standard"
onChange={handelInputChange} />
<TextField
name="desc"
label="Description"
variant="standard"
onChange={handelInputChange} />
<TextField
name="priority"
type="number"
label="Priority"
variant="standard"
onChange={handelInputChange} />
</Grid>
</Grid>
</form>
<button type="submit" variant="contained" color="primary">
Add
</button>
</Paper>
</>
);
}
You have wrong HTML structure. button[type=submit] should be inside <form> tag
In addition to Steve, You can use simply register function to do the work for you just supply register function in the inputRef of your MUI Form Component.
import { Button, Grid, Paper, TextField } from "#mui/material";
import React from "react";
import { useForm } from "react-hook-form";
export default function Page2(props) {
const { handleSubmit, register } = useForm();
const handelInputChange = (e) => {
const { name, value } = e.target;
console.log(name, value);
};
const handleData = (data) => {
console.log("data",data);
};
return (
<>
<Paper
style={{ margin: "10px auto", textAlign: "center" }}
elevation={24} >
<h1 style={{ textAlign: "center" }}>Todo Application</h1>
<form onSubmit={handleSubmit(handleData)}>
<Grid
style={{ margin: "10px" }}
container
spacing={1}
direction="column" >
<Grid item xs={6}>
<TextField
name="title"
label="Title"
variant="standard"
inputRef={register}
onChange={handelInputChange} />
<TextField
name="desc"
label="Description"
variant="standard"
inputRef={register}
onChange={handelInputChange} />
<TextField
name="priority"
type="number"
label="Priority"
variant="standard"
inputRef={register}
onChange={handelInputChange} />
</Grid>
</Grid>
<button type="submit" variant="contained" color="primary">
Add
</button>
</form>
</Paper>
</>
);
}
You have quite a bit of things to do in order to get this form to console.log. First, as the other poster mentioned, the submit button needs to be within the form (and you probably want to uppercase that B in "<Button" so that you're using the MUI component.
<form onSubmit={handleSubmit(handleData)}>
<Grid
style={{ margin: "10px" }}
container
spacing={1}
direction="column"
>
<Grid item xs={6}>
<TextField
name="title"
label="Title"
variant="standard"
onChange={handelInputChange}
/>
...
</Grid>
</Grid>
// Moved and renamed here
<Button type="submit" variant="contained" color="primary">
Add
</Button>
</form>
That solves your submit problem, but then you will notice that the console.log("data") will only ever contain an empty object {} -- this is because react-form-hooks needs to be given a FormProvider and made aware of the form elements in the form that it should control. To do this you need to register the component. I have added working code example on one way to complete this task.
In this example, I created a generic FormFieldController wrapper that you can use to pass in whatever just about form fields you need. (I would not use this in production code, without cleanup, as it is only meant as an example):
const FormFieldController = ({
component: Component = TextField,
name = "",
defaultValue = "",
label = "",
validation = {},
required = false,
valueProp = "value",
callbackProp = "onChange",
onChange,
...rest
}) => {
const { control } = useFormContext();
return (
<Controller
name={name}
control={control}
defaultValue={defaultValue}
rules={validation}
render={({
field: { onChange: internalOnChange, value, ref },
fieldState: { error }
}) => {
const pipes = {
[valueProp]: value,
[callbackProp]: function () {
internalOnChange.apply(this, arguments);
// Middleman callback to allow for onChange back to the caller, if needed
if (onChange) {
onChange.apply(this, arguments);
}
}
};
return (
<>
<Component
id={name}
inputRef={ref}
caption={error ? error?.message : ""}
label={label}
{...pipes}
{...rest}
/>
</>
);
}}
/>
);
};
Working CodeSandbox Example

Reactjs TypeError: Cannot read property 'id' of undefined

I facing problem "TypeError: Cannot read property 'id' of undefined" when i using Grid in elements.
the error i facing like this.
Here is my sample code.
In this code only i am facing the issue when im using Grid
<ThemeProvider theme={theme}>
<Card>
<Edit {...props}>
<SimpleForm>
<Grid container spacing={1} align="center">
<Grid item sm={6}>
<ReferenceInput
source="appId"
reference="_apps"
allowEmpty
defaultValue={
props.location.data ? props.location.data.appId : ""
}
validate={required()}
>
<SelectInput optionText="label" />
</ReferenceInput>
</Grid>
<Grid item sm={6}>
<SelectInput
source="iconColor"
choices={[
{ id: "primary", name: "primary" },
{ id: "secondary", name: "secondary" },
{ id: "action", name: "action" },
{ id: "disabled", name: "disabled" },
]}
/>
</Grid>
<Grid item sm={6}>
<ReferenceManyField
label={"resources._fields.name"}
reference="_fields"
target="eid"
>
<Datagrid>
<TextInput type="text" source="label" />
<TextInput type="text" source="component" />
<BooleanField source="showInList" />
<BooleanField source="showInFilter" />
<BooleanField source="showInCreate" />
<BooleanField source="showInEdit" />
<BooleanField source="showInShow" />
<EditButton />
</Datagrid>
</ReferenceManyField>
</Grid>
<Grid item sm={6}>
<ReferenceManyField
label={"resources._triggers.name"}
reference="_triggers"
target="eid"
>
<Datagrid>
<TextInput type="text" source="name" />
<BooleanField source="beforeInsert" />
<BooleanField source="afterInsert" />
<BooleanField source="beforeUpdate" />
<BooleanField source="afterUpdate" />
<BooleanField source="beforeDelete" />
<BooleanField source="afterDelete" />
<EditButton />
</Datagrid>
</ReferenceManyField>
</Grid>
<Grid item sm={6}>
<AddTriggerButton />
<AddFieldButton />
</Grid>
</Grid>
</SimpleForm>
</Edit>
</Card>
</ThemeProvider>
This is my actual code in that screenshot:
const TriggerButton = ({ children, to, ...props }) => {
const CustomLink = React.useMemo(
() =>
React.forwardRef((linkProps, ref) => (
<StyledLink ref={ref} to={to} {...linkProps} />
)),
[to]
);
return (
<Button {...props} component={CustomLink}>
{children}
</Button>
);
};
export default class AddTriggerButton extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false,
props: props,
};
}
render() {
return (
<div>
<TriggerButton
component={Link}
to={{
pathname: "/_triggers/create",
data: { eid: this.state.props.record.id },
}}
startIcon={<AddIcon />}
>
New Trigger
</TriggerButton>
</div>
);
}
}
Because you don't pass any props to AddTriggerButton so props is {}. So this.state.props is {} and this.state.props.record become undefined.
This is not good logic. You need to pass props and use this.props instead this.state.props
<AddTriggerButton record={{id: value}} />
Change this.state.props.record.id to this.props.record.id
Try to console.log(this.state.props.record.id) and shate here the reault. How you defined your the props? Maybe there is an asynchronous problem, so try to put '?' before the id like this:
this.state.props.record?.id

React hook : How to call through multiple button inside a Class?

So i am using a React hook
import { useKeycloak } from '#react-keycloak/web';
import { useCallback } from 'react';
export const useAuthenticatedCallback = (callbackFn) => {
const [keycloak, initialized] = useKeycloak()
const authCallback = useCallback(() => {
// if user is not authenticated redirect to login
if (!keycloak.authenticated) {
return keycloak.login()
}
// otherwise invoke function
return callbackFn()
}, [callbackFn, initialized, keycloak])
return authCallback
}
and used in react class like a component
function AuthenticatedCallback(props) {
const authenticatedCallback = useAuthenticatedCallback(props);
return props.children(authenticatedCallback);
}
class Posts extends React.Component {
constructor() {
super()
handleTradeCallSubmit(){
if(this.state.tradeCallFormValid){
// To DO
this.setState({ ...this.state, tradeCallFormValid: false});
let _postForm = this.state.postForm;
let _companyCode = this.state.companyCode;
let requestBody = {
eventType:'create-trade-call-post',
callType:_postForm.tradeTypeId,
symbol:_companyCode,
userId: this.props.activeUser.Id,
price:_postForm.price,
stopLoss:_postForm.stopLoss,
targetPrice:_postForm.targetPrice,
targetDate:_postForm.targetDate,
tags: _companyCode,
title:_postForm.title,
notes:_postForm.notes
}
postService.create(requestBody)
.then((result) => {
NotificationManager.success(`Trade call post created successfully...`);
this.loadPosts(1);
this.clearTradeCallForm();
}).catch((error) => {
NotificationManager.error(`Trade call post creation failed..`);
console.log(`Error: ${error}`);
});
} else {
let _postForm = this.state.postForm;
_postForm.isValidationActive = true;
this.setState({ ...this.state, postForm: _postForm});
}
}
.............................
.............................
render() {
if (this.state.isLoading) {
return <CircularSpinner />;
}
return ( <AuthenticatedCallback handleTradeCallSubmit={this.handleTradeCallSubmit}>{authenticatedCallback =>
<div>
<NotificationContainer/>
<Card>
<CardContent>
<form ref={(ref) => this.formRef = ref} noValidate autoComplete="off">
<Grid className="text-center" container spacing={2}>
{
this.state.postTypes.map((postType, index) =>
<Grid key={postType.Id} item sm={6} xs={6} md={3}>
<h5>{postType.Name} <Switch key={postType.Id} checked={(postType.Name === 'TradeCall')?this.state.isTradeCallActive: !this.state.isTradeCallActive} value={postType.Id} onChange={this.handleChange} name={postType.Name} inputProps={(postType.Name === 'TradeCall') ? {'aria-label': 'secondary checkbox' }: { 'aria-label': 'primary checkbox' }} /></h5>
</Grid>
)
}
<div className={!this.state.isTradeCallActive ? 'hidden' : ''}>
<Grid container spacing={2}>
<Grid item sm={12} xs={12} md={2}>
<ButtonGroup fullWidth aria-label="small button group">
<Button onClick={()=>{this.setState({ ...this.state, tradeTypeSelected: "Sale"})}}
variant={(this.state.tradeTypeSelected === "Buy") ? "outlined" : "contained"}
color={(this.state.tradeTypeSelected === "Buy") ? "default" : "secondary"}> Sale
</Button>
<Button onClick={()=>{this.setState({ ...this.state, tradeTypeSelected: "Buy"})}}
variant={(this.state.tradeTypeSelected === "Buy") ? "contained" : "outlined"}
color={(this.state.tradeTypeSelected === "Buy") ? "secondary" : "default"}> Buy
</Button>
</ButtonGroup>
</Grid>
<Grid item sm={12} xs={12} md={2}>
<TextField fullWidth id="txtPrice" error={this.state.postForm.isValidationActive && !this.state.postForm.priceValid} name="txtPrice" type="number" InputProps={{ inputProps: { min: 0} }} size="small" label="Price" onChange={this.handleChange} variant="outlined" placeholder="Price.." />
</Grid>
<Grid item sm={12} xs={12} md={2}>
<TextField fullWidth id="txtStoploss" error={this.state.postForm.isValidationActive && !this.state.postForm.stopLossValid} name="txtStoploss" type="number" InputProps={{ inputProps: { min: 0} }} size="small" label="Stoploss" onChange={this.handleChange} variant="outlined" placeholder="SL.." />
</Grid>
<Grid item sm={12} xs={12} md={2}>
<TextField fullWidth id="txtTarget" error={this.state.postForm.isValidationActive && !this.state.postForm.targetPriceValid} name="txtTarget" type="number" InputProps={{ inputProps: { min: 0} }} size="small" label="Target price" onChange={this.handleChange} variant="outlined" placeholder="Price.." />
</Grid>
<Grid item sm={12} xs={12} md={4}>
<TextField fullWidth id="targetDate" error={this.state.postForm.isValidationActive && !this.state.postForm.targetDateValid} name="targetDate" onChange={this.handleChange} type="date" size="small" label="Target date" variant="outlined" InputLabelProps={{ shrink: true, }} />
</Grid>
</Grid>
<Grid justify="center" container spacing={2}>
<Grid item sm={12} xs={12} md={3}>
<Button size="medium" fullWidth id="btnSubmit" startIcon={<SaveIcon />} onClick={authenticatedCallback} variant="contained" color="primary"> Save </Button>
</Grid>
</Grid>
</div>
}
</AuthenticatedCallback>)
}
}
// Map redux state to props
const mapStateToProps = state => ({
activeUser: state.session.activeUser
});
// export the component.
export default connect(mapStateToProps)(Posts);
Now in button i am calling it like this
<Button size="medium" fullWidth id="btnSubmit" startIcon={<SaveIcon />} onClick={authenticatedCallback} variant="contained" color="primary"> Save </Button>
But i have a multiple button here inside this react class what will approach to call same React hook to check user login or not?
So here is one Solution I got with one of my friend
suggest in Hook Component function
function AuthenticatedCallback(props) {
const authenticatedCallback = useAuthenticatedCallback(props.handleTradeCallSubmit);
const authenticatedCallback1 = useAuthenticatedCallback(props.handleAnalysisSubmit);
return props.children(authenticatedCallback,authenticatedCallback1);
}
and changes in class level
<AuthenticatedCallback handleTradeCallSubmit={this.handleTradeCallSubmit} handleAnalysisSubmit={this.handleAnalysisSubmit}>{(authenticatedCallback,authenticatedCallback1) =>
<div>
<NotificationContainer/>
.............................
.............................
<Button size="medium" fullWidth id="btnSubmit" startIcon={<SaveIcon />} onClick={authenticatedCallback} variant="contained" color="primary"> Save </Button>
<Button fullWidth size="medium" id="btnAnalysisSubmit" startIcon={<SaveIcon />} onClick={authenticatedCallback1} variant="contained" color="primary"> Save </Button>
</div>
}
</AuthenticatedCallback>)
}
}

Categories

Resources