unable to use MaterialUI Datepicker,Dayjs with useFormik and Yup - javascript

I am using Material UI Date picker with day js,but the issue that arising again and again is,'when I select the date on calender,1st time it updates in textfield and then it is not working.And also having problem in Yup like when touched 1st time it gives error means works perfectly but when removing the date from text field and left the field blank it does not work.'
codesandbox Link : https://codesandbox.io/s/material-ui-datepicker-error-pdvt07
code:
import "./styles.css";
import React, { useState } from "react";
import {
TextField,
Container,
Typography,
Stack,
Button,
Box
} from "#mui/material";
import { Link } from "react-router-dom";
import { Helmet } from "react-helmet-async";
import { styled } from "#mui/material/styles";
import { AdapterDayjs } from "#mui/x-date-pickers/AdapterDayjs";
import { DatePicker } from "#mui/x-date-pickers/DatePicker";
import { DesktopDatePicker } from "#mui/x-date-pickers/DesktopDatePicker";
import TodayIcon from "#mui/icons-material/Today";
import moment from "moment";
import dayjs from "dayjs";
import { LocalizationProvider } from "#mui/x-date-pickers/LocalizationProvider";
import InputAdornment from "#mui/material/InputAdornment";
import Autocomplete from "react-google-autocomplete";
import { useFormik } from "formik";
import * as Yup from "yup";
// import useResponsive from "../../hooks/useResponsive";
export default function App() {
// const navigate = useNavigate();
const validationSchema = Yup.object().shape({
firstName: Yup.string().required("First Name is required"),
lastName: Yup.string()
// .length(3, 'Last Name must be greater than 3 characters')
.required("Last Name is required"),
email: Yup.string()
.email("Invalid email")
.required("Please enter your email"),
mobile: Yup.string()
.length(10, "Mobile Number must be 10 digit")
.required("Mobile Number is required"),
dob: Yup.string().required("Dob is required"),
passingYear: Yup.string().required("Passing out year is required"),
location: Yup.string().required("Location is required"),
occupation: Yup.string().required("Occupation is required"),
address: Yup.string().required("Addres is required")
});
const formik = useFormik({
initialValues: {
firstName: "",
lastName: "",
email: "",
mobile: "",
dob: "",
passingYear: "",
location: "",
address: "",
occupation: ""
},
validationSchema,
onSubmit: (values) => {
console.log(values);
// navigate(`/verify-otp?email=${values.email}`, { replace: true });
}
});
return (
<div className="App">
<form onSubmit={formik.handleSubmit}>
<Stack direction={"column"} spacing={3}>
<Box>
<TextField
sx={{
width: "100%"
}}
id="outlined-firstName-input"
label="First Name"
name="firstName"
type={"text"}
onChange={formik.handleChange}
value={formik.values.firstName}
onBlur={formik.handleBlur}
autoComplete="off"
/>
{formik.touched.firstName && formik.errors.firstName && (
<p
style={{
color: "red",
marginTop: "5px",
marginBottom: "-15px"
}}
>
{formik.errors.firstName}
</p>
)}
</Box>
<Box>
<TextField
sx={{
width: "100%"
}}
id="outlined-lastName-input"
label="Last Name"
name="lastName"
type={"text"}
onChange={formik.handleChange}
value={formik.values.lastName}
onBlur={formik.handleBlur}
autoComplete="off"
/>
{formik.touched.lastName && formik.errors.lastName && (
<p
style={{
color: "red",
marginTop: "5px",
marginBottom: "-15px"
}}
>
{formik.errors.lastName}
</p>
)}
</Box>
<Box>
<TextField
sx={{
width: "100%"
}}
id="outlined-email-input"
label="Email address"
name="email"
type={"email"}
onChange={formik.handleChange}
value={formik.values.email}
onBlur={formik.handleBlur}
/>
{formik.touched.email && formik.errors.email && (
<p
style={{
color: "red",
marginTop: "5px",
marginBottom: "-15px"
}}
>
{formik.errors.email}
</p>
)}
</Box>
<Box>
<TextField
sx={{
width: "100%"
}}
InputProps={{
startAdornment: (
<InputAdornment position="start">+91</InputAdornment>
)
}}
id="outlined-mobile-input"
label="Mobile Number"
type="tel"
name="mobile"
onChange={formik.handleChange}
value={formik.values.mobile}
onBlur={formik.handleBlur}
autoComplete="off"
/>
{formik.touched.mobile && formik.errors.mobile && (
<p
style={{
color: "red",
marginTop: "5px",
marginBottom: "-15px"
}}
>
{formik.errors.mobile}
</p>
)}
</Box>
<Box
sx={{
width: "100%"
}}
>
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DesktopDatePicker
label="Date of birth"
inputFormat="DD/MM/YYYY"
value={dayjs(formik.values?.dob).format("DD-MM-YYYY") || ""}
onChange={(newValue) => {
formik.setFieldValue(
"dob",
dayjs(newValue).format("DD-MM-YYYY")
);
formik.setFieldTouched("dob", true);
}}
renderInput={(params) => (
<TextField
sx={{
width: "100%"
}}
{...params}
name="dob"
onBlur={formik.handleBlur}
error={formik.errors.dob && formik.touched.dob}
/>
)}
/>
</LocalizationProvider>
{formik.touched.dob && formik.errors.dob && (
<p
style={{
color: "red",
marginTop: "5px",
marginBottom: "-15px"
}}
>
{formik.errors.dob}
</p>
)}
</Box>
<Box
sx={{
width: "100%"
}}
>
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DatePicker
views={["year"]}
label="Passing year"
maxDate={dayjs().subtract(1, "year")}
value={formik.values.passingYear || ""}
onBlur={formik.handleBlur}
onChange={(newValue) => {
formik.setFieldValue("passingYear", newValue?.format("YYYY"));
}}
renderInput={(params) => (
<TextField
sx={{
width: "100%"
}}
{...params}
name="passingYear"
onBlur={formik.handleBlur}
error={
formik.errors.passingYear && formik.touched.passingYear
}
/>
)}
/>
{formik.touched.passingYear && formik.errors.passingYear && (
<p
style={{
color: "red",
marginTop: "5px",
marginBottom: "-15px"
}}
>
{formik.errors.passingYear}
</p>
)}
</LocalizationProvider>
</Box>
<Box>
<TextField
sx={{
width: "100%"
}}
id="outlined-occupation-input"
label="Occupation"
name="occupation"
type={"text"}
onChange={formik.handleChange}
value={formik.values.occupation}
onBlur={formik.handleBlur}
autoComplete="off"
/>
{formik.touched.occupation && formik.errors.occupation && (
<p
style={{
color: "red",
marginTop: "5px",
marginBottom: "-15px"
}}
>
{formik.errors.occupation}
</p>
)}
</Box>
<Box>
<Autocomplete
className="location"
style={{
width: "100%",
paddingLeft: "13px",
height: "8vh",
border: "1px solid rgb(224,224,224)",
borderRadius: "6px",
fontSize: "17px",
fontWeight: "500",
color: "#212B36",
backgroundColor: "#F9FAFB",
"&:focus": {
borderWidth: "2px",
borderColor: "darken(#2f8f1f, 5%)",
fontSize: "20px"
}
}}
apiKey={"AIzaSyABX4LTqTLQGg_b3jFOH8Z6_H5CDqn8tbc"}
onPlaceSelected={(place) => {
formik.setFieldValue("location", place?.formatted_address);
}}
types={["address"]}
componentRestrictions={{ country: "us" }}
name="location"
onChange={formik.handleChange}
onBlur={formik.handleBlur}
/>
{formik.touched.location && formik.errors.location && (
<p
style={{
color: "red",
marginTop: "5px",
marginBottom: "-15px"
}}
>
{formik.errors.location}
</p>
)}
</Box>
<Box
sx={{
width: "100%"
}}
>
<TextField
sx={{
width: "100%"
}}
id="outlined-password-input"
label="Addres"
name="address"
value={formik.values.address}
onChange={formik.handleChange}
onBlur={formik.handleBlur}
type="text"
multiline
rows={4}
maxRows={6}
autoComplete="off"
/>
{formik.touched.address && formik.errors.address && (
<p
style={{
color: "red",
marginTop: "5px",
marginBottom: "-15px"
}}
>
{formik.errors.address}
</p>
)}
</Box>
<Box ml={"auto"}>
<Button fullWidth size="large" type="submit" variant="contained">
Sign Up
</Button>
</Box>
</Stack>
</form>
</div>
);
}
Thanks in advance.....

you need to use dayjs format when trying to display the date. the date picker already formats the date for you in the textfield.
<DesktopDatePicker
label="Date of birth"
inputFormat="DD/MM/YYYY"
value={formik.values?.dob}
onChange={(newValue) => {
formik.setFieldValue(
"dob",
newValue
);
formik.setFieldTouched("dob", true);
}}
renderInput={(params) => (
<TextField
sx={{
width: "100%"
}}
{...params}
name="dob"
onBlur={formik.handleBlur}
error={formik.errors.dob && formik.touched.dob}
/>
)}
/>

Related

ReactJS - Material UI - Box width inconsistent different between pages with the same amount of px

I'm dealing with a silly issue here. I've got a fresh project in Reaction 17.0.2 and I've got two pages with the same layout: A Box with some TextFields. I've set the maxWidth of both boxes to be 700px, yet one is wider than the other? It's really bothering me, I've double checked everything, what can be the cause of this?
AddMenu
return (
<Box
flexDirection="column"
justifyContent="center"
sx={{ maxWidth: "700px", m: 5, bgcolor: "cyan" }}
>
<TextField
type="text"
id="name"
required
value={menu.name}
onChange={handleMenuChange}
label="Name"
name="name"
sx={{ width: "100%", height: "60px" }}
/>
<TextField
type="text"
id="description"
required
value={menu.description}
onChange={handleMenuChange}
label="Description"
name="description"
sx={{ width: "100%", mt: 2, height: "60px" }}
/>
<TextField
required
type="number"
id="price"
value={menu.price}
onChange={handleMenuChange}
label="Price"
name="price"
sx={{ width: "100%", mt: 2, height: "60px" }}
/>
<Button
variant="outlined"
onClick={submitMenu}
sx={{ width: "100%", mt: 2, height: "60px" }}
>
Submit
</Button>
</Box>
);
UpdateMenu
return (
<Box
flexDirection="column"
justifyContent="center"
sx={{ maxWidth: "700px", m: 5, bgcolor: "cyan" }}
>
<TextField
required
type="text"
id="name"
value={currentMenu.name}
onChange={handleMenuChange}
label="Name"
name="name"
sx={{ width: "100%", mt: 2, height: "60px" }}
/>
<TextField
required
type="text"
id="description"
value={currentMenu.description}
onChange={handleMenuChange}
label="Description"
name="description"
sx={{ width: "100%", mt: 2, height: "60px" }}
/>
<TextField
required
type="number"
id="price"
value={currentMenu.price}
onChange={handleMenuChange}
label="Price"
name="price"
sx={{ width: "100%", mt: 2, height: "60px" }}
/>
<Box
sx={{
display: "flex",
}}
>
<Button
variant="contained"
onClick={updateMenu}
sx={{ width: "100%", mt: 2, mr: 2, height: "60px" }}
>
Update
</Button>
<Button
variant="outlined"
onClick={() => navigate("/")}
sx={{ width: "100%", mt: 2, height: "60px" }}
>
Return
</Button>
</Box>
</Box>
);
App
function App() {
return (
<Box height="100vh">
<AppBar position="static">
<Toolbar>
<MenuItem component={Link} to="/">
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
Menu
</Typography>
</MenuItem>
<MenuItem component={Link} to="/add">
<Typography textAlign="center">Add</Typography>
</MenuItem>
<Box sx={{ flexGrow: 1 }} />
<Button color="inherit">Login</Button>
</Toolbar>
</AppBar>
<Box
sx={{
backgroundColor: "#EAECEE",
display: "flex",
justifyContent: "center",
height: "100%",
}}
>
<Routes>
<Route path={"/"} element={<MenuList />} />
<Route path={"/menus"} element={<MenuList />} />
<Route path={"/add/"} element={<AddMenu />} />
<Route path={"/menu/:id/update/"} element={<UpdateMenu />} />
</Routes>
</Box>
</Box>
);
}
export default App;
Inspect

Whenever invite button is clicked new form should be added everytime and when delete button clicked form gets deleted can anyone help me in this?

Invite.js
this is my invite component in which invite button is outside of the form and delete button is inside of form.I want if delete button is click form should be deleted In this I've used use state and I've have taken this form from material-ui help me if any one can how I can solve my problem ?
import * as React from "react";
import Box from "#mui/material/Box";
import FormControl from "#mui/material/FormControl";
import TextField from "#mui/material/TextField";
import AccountCircle from "#mui/icons-material/AccountCircle";
import Button from "#mui/material/Button";
import DeleteIcon from "#mui/icons-material/Delete";
import AddIcon from "#mui/icons-material/Add";
import Stack from "#mui/material/Stack";
const Invites = () => {
const [ addForm,setAddForm]=React.useState(false)
const [deleteForm, setdeleteForm]=React.useState(false)
const setAddFormHandler = () => {
console.log("clicked");
setAddForm(true);
};
const deleteHandler=()=>{
setdeleteForm(true)
}
return (
<>
<Stack direction="row" spacing={2}>
<Button
variant="contained"
color="info"
startIcon={<AddIcon />}
onClick={setAddFormHandler}
>
ADD INVITE
</Button>
</Stack>
{addForm ?<Box sx={{ "& > :not(style)": { m: 1 } }}>
<FormControl>
<Box sx={{ display: "flex", alignItems: "flex-end", marginTop: 2 }}>
<AccountCircle sx={{ color: "action.active", mr: 1, my: 0.5 }} />
<TextField
id="input-with-sx"
label="With sx"
variant="filled"
/>
</Box>
<Box sx={{ display: "flex", alignItems: "flex-end", marginTop: 2 }}>
<AccountCircle sx={{ color: "action.active", mr: 1, my: 0.5 }} />
<TextField
id="input-with-sx"
label="With sx"
variant="filled"
/>
</Box>
<Box sx={{ display: "flex", alignItems: "flex-end", marginTop: 2 }}>
<AccountCircle sx={{ color: "action.active", mr: 1, my: 0.5 }} />
<TextField
id="input-with-sx"
label="With sx"
variant="filled"
/>
</Box>
<Box sx={{ display: "flex", alignItems: "flex-end", marginTop: 2 }}>
<AccountCircle sx={{ color: "action.active", mr: 1, my: 0.5 }} />
<TextField
id="input-with-sx"
label="With sx"
variant="filled"
/>
</Box>
<Stack
direction="row"
spacing={4}
style={{ marginLeft: 30, marginTop: 18, width: 500 }}
>
<Button variant="contained" size="large" startIcon={<DeleteIcon />} onClick=
{deleteHandler}>
Delete
</Button>
</Stack>
</FormControl>
</Box>:null}
</>
);
};
export default Invites;
First of all your question is confusing. So i'm adding two solutions here which addresses two perspectives of the problem, you can choose the one matching yours.
Sol 1: You want to create new form for each click on invite button (multiple forms)
The below solution will add new forms to the same page every time the invite button is clicked and delete the respective form once the delete button is clicked.
import * as React from "react";
import Box from "#mui/material/Box";
import FormControl from "#mui/material/FormControl";
import TextField from "#mui/material/TextField";
import AccountCircle from "#mui/icons-material/AccountCircle";
import Button from "#mui/material/Button";
import DeleteIcon from "#mui/icons-material/Delete";
import AddIcon from "#mui/icons-material/Add";
import Stack from "#mui/material/Stack";
const Invites = () => {
const [forms, setForm] = React.useState({ val: []});
function createcustomForms() {
return forms.val.map((el, i) =>
<div key={i}>
<Box sx={{ "& > :not(style)": { m: 1 } }}>
<FormControl>
<Box sx={{ display: "flex", alignItems: "flex-end", marginTop: 2 }}>
<AccountCircle sx={{ color: "action.active", mr: 1, my: 0.5 }} />
<TextField
id="input-with-sx"
label="With sx"
variant="filled"
/>
</Box>
<Box sx={{ display: "flex", alignItems: "flex-end", marginTop: 2 }}>
<AccountCircle sx={{ color: "action.active", mr: 1, my: 0.5 }} />
<TextField
id="input-with-sx"
label="With sx"
variant="filled"
/>
</Box>
<Box sx={{ display: "flex", alignItems: "flex-end", marginTop: 2 }}>
<AccountCircle sx={{ color: "action.active", mr: 1, my: 0.5 }} />
<TextField
id="input-with-sx"
label="With sx"
variant="filled"
/>
</Box>
<Box sx={{ display: "flex", alignItems: "flex-end", marginTop: 2 }}>
<AccountCircle sx={{ color: "action.active", mr: 1, my: 0.5 }} />
<TextField
id="input-with-sx"
label="With sx"
variant="filled"
/>
</Box>
<Stack
direction="row"
spacing={4}
style={{ marginLeft: 30, marginTop: 18, width: 500 }}
>
<Button variant="contained" size="large" startIcon={<DeleteIcon />}
onClick={(e) => removeForm(i)}>
Delete
</Button>
</Stack>
</FormControl>
</Box>
</div>
);
}
const addForm = () => {
setForm({ val: [...forms.val, '']})
}
const removeForm = (i) => {
let vals = [...forms.val];
vals.splice(i,1);
setForm({ val: vals });
}
return (
<>
<Stack direction="row" spacing={2}>
<Button
variant="contained"
color="info"
startIcon={<AddIcon />}
onClick={addForm}
>
ADD INVITE
</Button>
</Stack>
{createcustomForms()}
</>
);
};
export default Invites;
Sol 2 : You want to create a form when invite button is clicked and delete it when delete button is clicked (currently in your code delete is not working)
const deleteHandler=()=>{
setdeleteForm(true)
}
should be changed to
const deleteHandler=()=>{
setAddForm(false);
}

React native invariant violation: text strings must be rendered within a <Text> component in a form (TextField)

This is my code for a form in React Native which is where i seem to be getting the error. I'm confused as this renders perfectly fine in my web simulator (expo):
working form but I get this error when I use ios simulator. I don't have any conditional logic or spaces/semicolons(at least what i can find) so not sure why I'm getting this error, also i'm using material ui core for my text fields in my form (which is where the error is supposedly coming from if you ref the image above). Any help would be appreciated!! pls help
import React, { useRef, useState } from 'react'
import { StyleSheet, View, Text, Modal } from 'react-native';
import { Formik, Form, FieldArray } from 'formik';
import { makeStyles } from '#material-ui/core/styles';
import { Button, TextField } from "#material-ui/core";
import { recipeService } from '../services/RecipeService';
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
flexWrap: 'wrap',
},
textField: {
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
marginTop: theme.spacing(1),
},
}));
export default function NewRecipe({ route }) {
const [showAlert, setShowAlert] = useState(false);
const { userId } = route.params;
const instructions = [''];
const ingredients = [{ name: '', amount: '', optional: false }];
const classes = useStyles();
const input = useRef();
return (
<View style={styles.container}>
<Formik
initialValues={{ userId: userId, name: "", summary: "", instructions: instructions, ingredients: ingredients }}
onSubmit={(values, actions) => {
recipeService.createRecipe(values).then(
(response) => {
console.log(response);
setShowAlert(true);
console.log("alert = " + showAlert);
actions.resetForm({});
return (
<Modal
animationType="slide"
transparent={false}
visible={true}
onRequestClose={
() => { setShowAlert(false); }
}>
<View style={styles.modalView}>
<Text>Recipe saved!</Text>
<Button
margin="normal"
type="button"
variant="contained"
color="default"
className={classes.textField}
onClick={() => actions.resetForm({})}
>
New Recipe
</Button>
</View>
</Modal>
)
}
)
.catch((error) => {
console.log(error);
});
}
}
>{({ values, handleChange, handleBlur }) => (
<Form>
<TextField
fullWidth
variant="outlined"
id="name"
name="name"
label="Name"
value={values.name}
onChange={handleChange}
/>
<TextField
fullWidth
multiline
variant="outlined"
id="summary"
name="summary"
label="Summary"
className={classes.textField}
value={values.summary}
onChange={handleChange}
/>
<View style={styles.row}>
<FieldArray
name="ingredients"
render={arrayHelpers => (
<div>
{values.ingredients.map((item, index) => (
<div key={index}>
<TextField
variant="outlined"
label="Ingredient Name"
name={`ingredients.${index}.name`}
value={item.name}
margin="normal"
className={classes.textField}
onChange={handleChange}
style={{ margin: 8, width: 233 }}
onBlur={handleBlur}
/>
<TextField
variant="outlined"
label="Amount"
name={`ingredients.${index}.amount`}
value={item.amount}
margin="normal"
className={classes.textField}
onChange={handleChange}
style={{ margin: 8, width: 100 }}
onBlur={handleBlur}
/>
<Button
margin="normal"
type="button"
color="secondary"
variant="outlined"
margin="dense"
style={{ margin: 8, width: 30 }}
className={classes.textField}
onClick={() => arrayHelpers.remove(index)}
> x
</Button>
<Button
margin="normal"
type="button"
variant="contained"
color="default"
className={classes.textField}
onClick={() => arrayHelpers.push({ name: '', amount: '', optional: false })}
>Add
</Button>
</div>
))}
</div>
)}
/>
</View>
<FieldArray
name="instructions"
render={arrayHelpers => (
<div>
{values.instructions.map((item, index) => (
<div key={index}>
<TextField
variant="outlined"
label="Instruction"
name={`instructions.${index}`}
value={item}
margin="normal"
className={classes.textField}
onChange={handleChange}
style={{ margin: 8, width: 350 }}
onBlur={handleBlur}
/>
<Button
margin="normal"
type="button"
color="secondary"
variant="outlined"
margin="dense"
style={{ margin: 8, width: 30 }}
className={classes.textField}
onClick={() => arrayHelpers.remove(index)}
> x
</Button>
</div>
))}
<Button
margin="normal"
type="button"
variant="contained"
color="default"
className={classes.textField}
onClick={() => arrayHelpers.push('')}
>Add
</Button>
</div>
)}
/>
<div>
<Button color="primary" variant="contained" className={classes.textField} fullWidth type="submit">
Submit
</Button>
</div>
</Form>
)}
</Formik>
You cannot use #material-ui/core for React Native projects.
#material-ui/core can work for expo because it's web based. But I'm pretty sure that it won't work for native environments.
I'd like to recommend alternatives, but I don't use material design for React Native because it simply doesn't fit to iOS.

Cannot read props of undefined

I am trying to add class form control for my select statement. However there is a problem which occurs. It shows props are undefined.
Here is the code:
const useStyles = makeStyles({
root: {
width: "100%",
maxWidth: 500
}
});
const classes = {
formControl: {
margin: this.props.theme.spacing(1),
minWidth: 120,
},
selectEmpty: {
marginTop: this.props.theme.spacing(2),
},
};
export class FormUserDetails extends Component {
constructor(props) {
super(props);
this.state = { KPI: [], addModalShow: false,age: "",
name: "hai" };
}
continue = e => {
e.preventDefault();
if (document.getElementById("Title").value.length < 5) {
document.getElementById("title").style.visibility = "visible";
document.getElementById("Title").style.border = "1px solid red";
// keep form from submitting
} else if (document.getElementById("Details").value.length < 10) {
document.getElementById("details").style.visibility = "visible";
document.getElementById("Details").style.border = "1px solid red";
// keep form from submitting
} else if (document.getElementById("What").value.length < 10) {
document.getElementById("what").style.visibility = "visible";
document.getElementById("What").style.border = "1px solid red";
// keep form from submitting
} else if (document.getElementById("Why").value.length < 10) {
document.getElementById("why").style.visibility = "visible";
document.getElementById("Why").style.border = "1px solid red";
// keep form from submitting
} else if (document.getElementById("How").value.length < 10) {
document.getElementById("how").style.visibility = "visible";
document.getElementById("How").style.border = "1px solid red";
// keep form from submitting
} else if (document.getElementById("Implementation_Status").value == "") {
document.getElementById("status").style.visibility = "visible";
document.getElementById("Status").style.border = "1px solid red";
// keep form from submitting
} else if (document.getElementById("Cost").value.length < 1) {
document.getElementById("cost").style.visibility = "visible";
document.getElementById("Cost").style.border = "1px solid red";
// keep form from submitting
} else if (document.getElementById("Benefits").value.length < 10) {
document.getElementById("benefits").style.visibility = "visible";
document.getElementById("Benefits").style.border = "1px solid red";
// keep form from submitting
} else {
// else form is good let it submit, of course you will
// probably want to alert the user WHAT went wrong.
this.props.nextStep();
}
};
handleSubmit(event) {
event.preventDefault();
fetch("https://localhost:44384/api/Details", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
TBD_ID: null,
TBD_TITLE: event.target.Title.value,
TBD_WHAT: event.target.What.value,
TBD_WHY: event.target.Why.value,
TBD_HOW: event.target.How.value,
TBD_STAGE: 1,
TBD_STATUS: event.target.Implementation_Status.value,
TBD_COST: event.target.Cost.value,
TBD_BENEFIT: event.target.Benefits.value,
TBD_BENEFIT_TYPE: 1,
TBD_FL_ACTIVE: null,
TBD_CRT_ID: null,
TBD_CRT_TS: null,
TBD_UPD_ID: null,
TBD_UPD_TS: null,
TBD_VALUE_ID: 2
})
})
.then(res => res.json())
.then(
result => {
alert(result);
},
error => {
alert("Failed");
}
);
}
//1
handleChangeRows = idx => e => {
const { Kpi_Before, value } = e.target;
const rows = [...this.state.rows];
rows[idx] = {
[Kpi_Before]: value
};
this.setState({
rows
});
};
//2
handleAddRow = () => {
const item = {
KPI_Before: "",
UOM_Before: "",
Base_Before: "",
Target_Before: "",
dateTime: ""
};
this.setState({
rows: [...this.state.rows, item]
});
};
//3
handleRemoveRow = () => {
this.setState({
rows: this.state.rows.slice(0, -1)
});
};
render() {
const { values, handleChange } = this.props;
const { deps } = this.state;
let { values1 } = this.state;
let addModalClose = () => this.setState({ addModalShow: false });
return (
<MuiThemeProvider theme={theme}>
<React.Fragment>
<div className={useStyles.root}>
<Grid item xs={12}>
<AppBar position="static">
<Toolbar>
<NavLink to="dashboard">
<DashboardIcon style={{ color: "white" }} />
</NavLink>
<Typography
align="center"
style={{ width: "100%", alignItems: "center" }}
>
Best Practices Management System
</Typography>
</Toolbar>
</AppBar>
</Grid>
</div>
<br />
<Form onSubmit={this.handleSubmit} style={{ marginLeft: "5%" }}>
<Grid container>
<Grid item xs={12}>
<TextField
label="Title"
variant="outlined"
size="small"
name="Title"
id="Title"
placeholder="Enter the Title of the Best Practice"
onChange={handleChange("Title")}
defaultValue={values.Title}
multiline
rows={1}
rowsMax={4}
style={{ width: "95%" }}
/>
<label
id="title"
style={{ visibility: "hidden", color: "red" }}
>
Title must be atleast 5 characters long
</label>
</Grid>
</Grid>
<Grid container>
<Grid item xs={6}>
<TextField
placeholder="Enter the details of the Best Practice"
label="Details of Best Practice"
id="Details"
size="small"
name="Details"
onChange={handleChange("Details")}
defaultValue={values.Details}
style={{ width: "90%" }}
variant="outlined"
multiline
rows={2}
rowsMax={4}
/>
<label
id="details"
style={{ visibility: "hidden", color: "red" }}
>
Details of Best Practice must be atleast 10 characters long
</label>
</Grid>
<Grid item xs={6}>
<TextField
placeholder="What is the Best Practice?"
label="What is the Best Practice"
size="small"
id="What"
name="What"
onChange={handleChange("What")}
defaultValue={values.What}
style={{ width: "90%" }}
variant="outlined"
multiline
rows={2}
rowsMax={4}
/>
<label id="what" style={{ visibility: "hidden", color: "red" }}>
What is the Best Practice must be atleast 10 characters long
</label>
</Grid>
</Grid>
<Grid container>
<Grid item xs={6}>
<TextField
placeholder="Why was the Best Practice Implemented"
label="Why was the Best Practice Implemented"
size="small"
name="Why"
id="Why"
onChange={handleChange("Why")}
defaultValue={values.Why}
style={{ width: "90%" }}
variant="outlined"
multiline
rows={2}
rowsMax={4}
/>
<label id="why" style={{ visibility: "hidden", color: "red" }}>
Why was the Best Practice implemented must be atleast 10
characters long
</label>
</Grid>
<Grid item xs={6}>
<TextField
placeholder="How was the Best Practice Implemented"
label="How was the Best Practice Implemented"
size="small"
name="How"
id="How"
onChange={handleChange("How")}
defaultValue={values.How}
style={{ width: "90%" }}
variant="outlined"
multiline
rows={2}
rowsMax={4}
/>
<label id="how" style={{ visibility: "hidden", color: "red" }}>
How was the Best Practice implemented must be atleast 10
characters long
</label>
</Grid>
</Grid>
<Grid container>
<Grid item xs={6}>
<FormControl id="Status" style={{ width: "90%" }} size="small">
<AddProcessModal
show={this.state.addModalShow}
onHide={addModalClose}
/>
<InputLabel
htmlFor="Implementation_Status"
id="Status"
style={{
marginLeft: 10,
top: "50%",
transform: "translate(0,-50%"
}}
>
Implementation Status
</InputLabel>
<Select
labelId="Implementation_Status"
name="Status"
id="Status"
onChange={handleChange("Status")}
defaultValue={values.Status}
variant="outlined"
inputProps={{
id: "Implementation_Status",
name: "age"
}}
>
<MenuItem value="1">Implemented</MenuItem>
<MenuItem value="2">Implementation in Progress</MenuItem>
<MenuItem value="3">Not Implemented</MenuItem>
</Select>
</FormControl>
<label
id="status"
style={{ visibility: "hidden", color: "red" }}
>
Implementation Status cannot be blank
</label>
</Grid>
<Grid item xs={6}>
<Form.Group controlId="TBD_COST">
<TextField
placeholder="Cost of Implementation of the Best Practice"
label="Cost of Implementation"
name="Cost"
id="Cost"
size="small"
onChange={handleChange("Cost")}
defaultValue={values.Cost}
style={{ width: "90%" }}
variant="outlined"
/>
<label
id="cost"
style={{ visibility: "hidden", color: "red" }}
>
Cost of Implementation cannot be left blank
</label>
</Form.Group>
</Grid>
</Grid>
<Grid container>
<Grid item xs={6}>
<TextField
placeholder="Benefits of the Best Practice"
label="Benefits of the Best Practice"
size="small"
name="Benefits"
id="Benefits"
onChange={handleChange("Benefits")}
defaultValue={values.Benefits}
style={{ width: "90%" }}
variant="outlined"
multiline
rows={2}
rowsMax={4}
/>
<label
id="benefits"
style={{ visibility: "hidden", color: "red" }}
>
Benefits must be at least 10 characters long
</label>
</Grid>
<Grid item xs={6}>
<FormControl className={classes.formControl} id="Process" style={{ width: "78%" }} size="small">
<InputLabel
htmlFor="Process"
id="Process"
style={{
marginLeft: 10,
top: "50%",
transform: "translate(0,-50%"
}}
>
Process
</InputLabel>
<Select
labelId="Process"
name="Process"
id="Process"
value={this.state.Process}
defaultValue={values.Process}
onChange={() => this.setState({ addModalShow: true })}
variant="outlined"
InputLabelProps={{
shrink: this.state.value ? true : false
}}
inputProps={{
name: "Process",
id: "Process"
}}
>
<option aria-label='None' value='' />
<option value={10}>Ten</option>
<option value={20}>Twenty</option>
<option value={30}>Thirty</option>
</Select>
</FormControl>
<Button
variant="outlined"
color="primary"
onClick={() => this.setState({ addModalShow: true })}
size="small"
style={styles.button2}
>
+
</Button>
<label
id="process"
style={{ visibility: "hidden", color: "red" }}
>
Process cannot be blank
</label>
</Grid>
</Grid>
<Grid
direction="row"
justify="right"
alignItems="right"
className="text-right"
style={{ width: "96%" }}
>
<Button
variant="contained"
size="small"
color="primary"
style={styles.button}
onClick={this.continue}
className="float-right"
>
Continue
</Button>
<Button
variant="contained"
size="small"
color="primary"
type="submit"
style={styles.button1}
>
Submit
</Button>
</Grid>
</Form>
</React.Fragment>
</MuiThemeProvider>
);
}
}
const theme = createMuiTheme({
palette: {
primary: blue,
secondary: purple
},
status: {
danger: "orange"
}
});
const styles = {
button: {
align: "right",
margin: 15,
marginRight: "1%"
},
button1: {
align: "right",
margin:15,
marginRight: "1%",
backgroundColor: "#21b6ae"
},
button2: {
margin: 2
}
};
export default FormUserDetails;
You probably dont require the jsx functions but please see what is the issue.
The code in short is this:
const classes = {
formControl: {
margin: this.props.theme.spacing(1),
minWidth: 120,
},
selectEmpty: {
marginTop: this.props.theme.spacing(2),
},
};
The code which I am using just to add the theme but there is an issue with props
In your code, this may point to window object, so it complains props are undefined
Have you tried
import { makeStyles } from '#material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
formControl: {
margin: theme.spacing(1),
minWidth: 120,
},
selectEmpty: {
marginTop: theme.spacing(2),
},
}));
and inside your component
const classes = useStyles();

Add to cart function using react

I am building a search filter of sorts using Elasticsearch and ReactiveSearch for UI.
Each result has an ID, title, etc that I can call to display it when a user searches. I need a button for each results, and when the user clicks it, it should 'add to cart' or something like that. I just need the clicked results to be shown in the next page.
The code below is my search field, and the results that are shown. I have an onclick function, but I don't know how to proceed after that. I think I need to use redux.
class Results extends Component {
render() {
return (
<ReactiveBase
app="datataglist"
credentials="mRgWyoKGQ:f47be2a6-65d0-43b6-8aba-95dbd49eb882"
url="https://scalr.api.appbase.io"
>
<DataSearch
componentId="search"
dataField={[
"maker_tag_name",
"maker_tag_name.autosuggest",
"maker_tag_name.keyword"
]}
fieldWeights={[6, 2, 6]}
fuzziness={1}
highlightField={["maker_tag_name"]}
placeholder="Search Tag Name"
style={{
marginBottom: 20
}}
title="Maker Tag Name"
/>
<SelectedFilters />
<ReactiveList
componentId="results"
dataField="_score"
pagination={true}
react={{
and: ["system", "grouping", "unit", "search"]
}}
size={10}
noResults="No results were found..."
renderItem={renderItem}
/>
</ReactiveBase>
);
}
}
function getNestedValue(obj, path) {
const keys = path.split(".");
const currentObject = obj;
const nestedValue = keys.reduce((value, key) => {
if (value) {
return value[key];
}
return "";
}, currentObject);
if (typeof nestedValue === "object") {
return JSON.stringify(nestedValue);
}
return nestedValue;
}
function renderItem(res, triggerClickAnalytics) {
let { url, unit, title, system, score, proposed, id } = {
title: "maker_tag_name",
proposed: "proposed_standard_format",
unit: "units",
system: "system",
score: "_score",
url: "",
id: "_id"
};
title = getNestedValue(res, title);
system = getNestedValue(res, system);
url = getNestedValue(res, url);
unit = getNestedValue(res, unit);
score = getNestedValue(res, score);
proposed = getNestedValue(res, proposed);
id = getNestedValue(res, id);
return (
<Row
onClick={triggerClickAnalytics}
type="flex"
gutter={16}
key={res._id}
style={{ margin: "20px auto", borderBottom: "1px solid #ededed" }}
>
<Col style={{ width: "360px" }}>
<h3
style={{ fontWeight: "600" }}
dangerouslySetInnerHTML={{
__html: title || "Choose a valid Title Field"
}}
/>
</Col>
<div style={{ padding: "20px" }} />
<Col>
<p
style={{ fontSize: "1em", width: "300px" }}
dangerouslySetInnerHTML={{
__html: system || "Choose a valid Description Field"
}}
/>
</Col>
<div style={{ padding: "10px" }} />
<Col>
<p
style={{ fontSize: "1em" }}
dangerouslySetInnerHTML={{
__html: unit || "-"
}}
/>
</Col>
<div style={{ padding: "10px" }} />
<Col style={{ minWidth: "120px" }}>
<p
style={{ fontSize: "1em", width: "300px"}}
dangerouslySetInnerHTML={{
__html: proposed || "Choose a valid Description Field"
}}
/>
</Col>
<div style={{ padding: "10px" }} />
<Col>
<p
style={{ fontSize: "1em"}}
dangerouslySetInnerHTML={{
__html: Math.round(score) || "Choose a valid Description Field"
}}
/>
</Col>
<Col>
<Button
shape="circle"
icon={<CheckOutlined />}
style={{ marginRight: "5px" }}
onClick={()=>{this.handleClick(id)}}
/>
</Col>
<Col style={{ minWidth: "120px" }}>
<p
style={{ fontSize: "1em", width: "300px"}}
dangerouslySetInnerHTML={{
__html: id || "Choose a valid Description Field"
}}
/>
</Col>
</Row>
);
}
export default Results;
Any help would be appreciated.

Categories