Radio checkboxes issue, don't work correctly? - radio-button

I'm using Semantic-ui-React library Trying to create Radio checkboxes,these checkboxes should be required. How can I do required for Radio buttons? Is there any way to make dropdown required in Semantic-ui-React?
import React, { Component } from 'react'
import { Divider,Label,List,Checkbox,Header } from 'semantic-ui-react'
handleRequest = (e, { value, label }) => {
this.setState({
redirect: false,
requestCategory: value,
typeOfRequest: label
});
}
<Form.Field>
<Form.Field>
<Checkbox className = 'radio'
required
label="New Solution"
name="typeOfRequest"
value={false}
checked={requestCategory === 'false'}
onChange={this.handleRequest}
/>
</Form.Field>
<Form.Field>
<Checkbox className = 'radio'
required
label="Enhancement to Existing Solution"
name="typeOfRequest"
value={'all'}
checked={requestCategory === 'all'}
onChange={this.handleRequest}
/>
</Form.Field>
<Form.Field>
<Checkbox className = 'radio'
required
label="Production Support"
name="typeOfRequest"
value={'all'}
checked={requestCategory === 'false'}
onChange={this.handleRequest}
/>
</Form.Field>
<Form.Field>
<Checkbox className = 'radio'
required
label="New Analysis"
name="typeOfRequest"
value={'all'}
checked={requestCategory === 'all'}
onChange={this.handleRequest}
/>
</Form.Field>
<Form.Field>
<Checkbox className = 'radio'
required
label="Existing Analysis"
name="typeOfRequest"
value={'all'}
checked={requestCategory === 'all'}
onChange={this.handleRequest}
/>
</Form.Field>
</Form.Field>

To make your checkbox field required, you just need to add the required props on the <Form.Field> component :
<Form.Field required>
<Checkbox
radio
label="Existing Analysis"
name="typeOfRequest"
value={'all'}
checked={requestCategory === 'all'}
onChange={this.handleRequest}
/>
</Form.Field>

Related

Material UI TextField select not showing initial value on form edit

I have an edit form in a modal that lets you edit user info. Here is the relevant portion:
export const EditUserModal = (Props) => {
const [formValues, setFormValues] = useState(Props.userData);
const [reporterData, setReporterData] = React.useState<any[]>([]);
React.useEffect(() => {
let apiClient = new APIClient();
apiClient.getOwners().then((response) => {
setReporterData(response);
});
}, []);
const handleInputChange = (e) => {
const { name, value } = e.target;
setFormValues({
...formValues,
[name]: value,
});
};
return (
<>
<Modal
open={Props.show}
onClose={() => { Props.toggleModal(false)}}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box
component="form"
autoComplete="off"
>
<Typography id="modal-modal-title" variant="h4" component="h4">
Edit User {Props.userData.name}
</Typography>
<div>
<TextField
required
id="outlined-select-basic"
select
name="reports_to"
label="Reports To"
value={formValues.reports_to}
onChange={handleInputChange}
>
{reporterData.map((option) => (
<MenuItem key={option.owner} value={option.owner}>
{option.owner}
</MenuItem>
))}
</TextField>
</div>
</Box>
</Modal>
</>
)
};
The TextField is supposed to show the initial value of {formValues.reports_to}, but it remains blank (the value is still correct) until you make a new selection. reporterData just returns a list of names(string).
I have tried adding it as a defaultValue, which did not work.

How to toggle show hide functionality for multiple fields in formik?

import React, { Fragment, useState, useEffect } from "react";
import { useSelector, useDispatch, connect } from "react-redux";
import { useNavigate } from "react-router";
import { Field, Form, Formik } from "formik";
import VisibilityIcon from "#material-ui/icons/Visibility";
import VisibilityOffIcon from "#material-ui/icons/VisibilityOff";
import { changePassword } from "../../Redux/Actions/changePasswordAction";
import { passwordErrors, roles } from "../Shared/constants";
import Alert from "../Modal/modal";
import "./ChangePassword.css";
function ChangePassword() {
const [showPassword1, setShowPassword1] = useState(false);
const [showPassword2, setShowPassword2] = useState(false);
const [showPassword3, setShowPassword3] = useState(false);
const alert = useSelector((state) => state.alert);
enter code here
const role_id = localStorage.getItem("role_id");
//Redux Dispatch:
const dispatch = useDispatch();
//Used to navigate
const navigation = useNavigate();
const passwords = {
currentPassword: "",
newPassword: "",
confirmNewPassword: "",
};
// function toggleShowPassword(clickedField) {
// if (clickedField === showPassword1) {
// setShowPassword1(!showPassword1) &&
// setShowPassword2(showPassword2) &&
// setShowPassword3(showPassword3);
// } else if (clickedField === showPassword2) {
// setShowPassword2(!showPassword2) &&
// setShowPassword1(showPassword1) &&
// setShowPassword3(showPassword3);
// } else {
// setShowPassword3(!showPassword3) &&
// setShowPassword1(showPassword1) &&
// setShowPassword2(showPassword2);
// }
// }
function toggleShowPassword1() {
setShowPassword1(!showPassword1);
}
function toggleShowPassword2() {
setShowPassword2(!showPassword2);
}
function toggleShowPassword3() {
setShowPassword3(!showPassword3);
}
//Alert
useEffect(() => {
if (Number(role_id) === roles.TRAINER_ROLE_ID) {
if (alert.type === "success_clear") {
navigation("/trainer-profile");
}
} else {
if (alert.type === "success_clear") {
navigation("/user-profile");
}
}
}, [alert, navigation, role_id]);
function validate(passwords) {
const errors = {};
if (passwords.currentPassword === "") {
errors.currentPassword = passwordErrors.PASSWORD;
}
if (passwords.newPassword === passwords.currentPassword) {
errors.newPassword = passwordErrors.OLD_NEW_SAME;
}
if (passwords.newPassword === "") {
errors.newPassword = passwordErrors.PASSWORD;
} else if (
!/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##%&])(?=.{8,})/.test(
passwords.newPassword
)
) {
errors.newPassword = passwordErrors.PASSWORD_INVALID;
}
if (passwords.confirmNewPassword === "") {
errors.confirmNewPassword = passwordErrors.CONFIRM_PASSWORD;
} else if (passwords.confirmNewPassword !== passwords.newPassword) {
errors.confirmNewPassword = passwordErrors.PASSWORDS_UNMATCHED;
}
return errors;
}
function handleChangePassword(passwords) {
const id = localStorage.getItem("user_id");
const passwordsData = {
oldPassword: passwords.currentPassword,
password: passwords.confirmNewPassword,
};
dispatch(changePassword(id, passwordsData));
}
return (
<Fragment>
<div className="row">
<div className="col">
<span className="main-heading mx-4">Change Account Password</span>
<div className="mx-4">
<hr></hr>
</div>
</div>
</div>
{alert.message && <Alert show={true} />}
<div className="passwords">
<Formik
initialValues={passwords}
validate={(values) => validate(values)}
onSubmit={(values) => handleChangePassword(values)}
>
{({ errors, touched }) => (
<Form>
<div className="row">
<div className="col-md">
<div className="form-group mb-4">
<label htmlFor="currentPassword" className="cp-label">
Current Password
</label>
<div className="input-group">
<Field
type={showPassword1 ? "text" : "password"}
id="currentPassword"
name="currentPassword"
placeholder="Enter your Current password"
className={
errors.currentPassword && touched.currentPassword
? "form-control primary-input-field is-invalid pass"
: "form-control primary-input-field pass"
}
/>
<span
className="input-group-text"
id="basic-addon2"
// onClick={() => toggleShowPassword(showPassword1)}
onClick={toggleShowPassword1}
>
{showPassword1 ? (
<VisibilityIcon
fontSize="small"
className="iconColor"
/>
) : (
<VisibilityOffIcon
fontSize="small"
className="iconColor"
/>
)}
</span>
{touched.currentPassword && errors.currentPassword ? (
<div className="invalid-feedback">
{errors.currentPassword}
</div>
) : null}
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-md">
<div className="form-group mb-4">
<label htmlFor="newPassword" className="cp-label">
New Password
</label>
<div className="input-group">
<Field
type={showPassword2 ? "text" : "password"}
id="newPassword"
name="newPassword"
placeholder="Enter your New password"
className={
errors.newPassword && touched.newPassword
? "form-control primary-input-field is-invalid pass"
: "form-control primary-input-field pass"
}
/>
<span
className="input-group-text"
id="basic-addon2"
// onClick={() => toggleShowPassword(showPassword2)}
onClick={toggleShowPassword2}
>
{showPassword2 ? (
<VisibilityIcon
fontSize="small"
className="iconColor"
/>
) : (
<VisibilityOffIcon
fontSize="small"
className="iconColor"
/>
)}
</span>
{touched.newPassword && errors.newPassword ? (
<div className="invalid-feedback">
{errors.newPassword}
</div>
) : null}
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-md">
<div className="form-group mb-4">
<label htmlFor="confirmNewPassword" className="cp-label">
Confirm New Password
</label>
<div className="input-group">
<Field
type={showPassword3 ? "text" : "password"}
id="confirmNewPassword"
name="confirmNewPassword"
placeholder="Confirm your New password"
className={
errors.confirmNewPassword &&
touched.confirmNewPassword
? "form-control primary-input-field is-invalid pass"
: "form-control primary-input-field pass"
}
/>
<span
className="input-group-text"
id="basic-addon2"
// onClick={() => toggleShowPassword(showPassword3)}
onClick={toggleShowPassword3}
>
{showPassword3 ? (
<VisibilityIcon
fontSize="small"
className="iconColor"
/>
) : (
<VisibilityOffIcon
fontSize="small"
className="iconColor"
/>
)}
</span>
{touched.confirmNewPassword &&
errors.confirmNewPassword ? (
<div className="invalid-feedback">
{errors.confirmNewPassword}
</div>
) : null}
</div>
</div>
</div>
</div>
<div className="row mt-4">
<div className="col text-end">
<button className="btn primary-button" type="submit">
Change Password
</button>
</div>
</div>
</Form>
)}
</Formik>
</div>
</Fragment>
);
}
const mapStateToProps = (state) => ({
changePassword: state.changePassword,
});
export default connect(mapStateToProps, {
changePassword,
})(ChangePassword);
Please someone help me to apply only one function that can toggle show and hide for three fields, I have already tried one function but it's not working. I couldn't know what to do ? I need one function there to toggle eye symbol when it is clicked, but with the function I have used it's changing and I am pressing for one field and another field's being shown, please someone explain me

why getting error while uploading image in react

I created a form with name, order, image, status feild in my application. I used material design for form design and used react-material-file-upload for image upload.i got the values and viewed in console.After submitting the form it is not added in my web api,getting error in file.filename not defined in server.
Add.js
import FileUpload from "react-material-file-upload";
import TextField from '#mui/material/TextField';
import Grid from '#mui/material/Grid';
function Addcategory(props){
const [files, setFiles] = useState([]);
const handleSubmit =async (event) =>{
event.preventDefault();
const userid=localStorage.getItem("id");
const fileimg =files[0];
console.log(fileimg);
const userData = {
catname:event.target[0].value,
catorder:event.target[2].value,
image:fileimg,
enable:event.target[4].value,
status:1,
createdBy:userid
}
console.log(userData);
await CategoryDataService.create(userData)
.then(res => {
const data=res.data;
console.log(res);
toast.success("Category Added Successfully");
})
.catch((err) => {
// console.log("err",err.response);
toast.error("please try again!");
});
}
return(
<ThemeProvider theme={theme}>
<div style={{ margin:" 30px 130px 30px"}}>
<Box sx={{ border: '2px solid #15171c', borderRadius: '10px'}} >
<Grid container rowSpacing={1} columnSpacing={{ xs: 1, sm: 2, md: 3 }}>
<Grid item xs={12} style={{textAlign:"center"}}>
<h2 style={{textAlign:"center"}}>Category Add</h2>
<Box
component="form"
sx={{
'& .MuiTextField-root': { m: 1,},
}}
onSubmit={handleSubmit}
noValidate
autoComplete="off"
>
<div className="form-display">
<Grid >
<TextField
required
id="outlined-text"
label="Category Name"
name="catname"
autoFocus/>
<TextField
id="outlined-text"
label="Category Order"
name="catorder"
type="number"
/>
<TextField
id="outlined-select-currency"
select
label="Category Status"
name="enable"
helperText="Please select actegory status"
>
{catStatus.map((option) => (
<MenuItem key={option.value} value={option.value} >
{option.label}
</MenuItem>
))}
</TextField>
<Grid item xs={12} columnSpacing={{xs:1}}>
<Grid item xs={12}>
<FileUpload value={files} onChange={setFiles} />
</Grid>
</Grid>
<Stack direction="row" spacing={2} justifyContent="center"
style={{margin:"15px"}}>
<Button variant="outlined" type="submit">
Submit {props.children}
</Button >
<Button variant="outlined" onClick={back}>
Cancel
</Button>
</Stack>
</Grid>
</div>
</Box>
</Grid>
</Grid>
</Box>
</div>
</ThemeProvider>
);
}
server.js
const multer=require("multer");
const fileStorageEngine = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./uploads");
},
filename:(req, file, cb) =>{
cb(null, Date.now() + "-" + file.originalname);
}
});
const upload = multer({ storage: fileStorageEngine });
app.post('/addCategory', upload.single("image"), async(req,res)=>{
// let file = req.file;
const data={
category_order:req.body.catorder,
category_name:req.body.catname,
category_icon:req.file.filename,
category_enable_disable:req.body.enable,
status:req.body.status,
created_by:req.body.createdBy,
createdAt:Date.now()
}
await models.category.create(data).then(result=>{
res.status(201).json({
Code: "1",
Message: "Category created successfully",
Data: result
});
})
.catch(error=>{
res.status(500).json({
Code: "0",
Message: "Something went wrong,try again.",
Post: error
});
})
});
this api is working in postman but not working while submit the form

react native multistep wizard formik yup

Hi I am new to react native.
I have react native project in which I have implement multistep form wizard with formik yup validation. Currently I have implemented multistep form wizard with formik yup validation in react.
How can I implement or convert it to react native.
Below is the code which implement in react.
import React, { useState } from 'react';
import { ErrorMessage, Field, Form, Formik } from "formik";
import * as Yup from "yup";
const Wizard = ({ children, initialValues, onSubmit }) => {
const [stepNumber, setStepNumber] = useState(0);
const steps = React.Children.toArray(children);
const [snapshot, setSnapshot] = useState(initialValues);
const step = steps[stepNumber];
const totalSteps = steps.length;
const isLastStep = stepNumber === totalSteps - 1;
const next = values => {
setSnapshot(values);
setStepNumber(Math.min(stepNumber + 1, totalSteps - 1));
};
const previous = values => {
setSnapshot(values);
setStepNumber(Math.max(stepNumber - 1, 0));
};
const handleSubmit = async (values, formikBag) => {
if (isLastStep) {
return onSubmit(values, formikBag);
} else {
next(values);
}
};
return (
<Formik
initialValues={snapshot}
onSubmit={handleSubmit}
validationSchema={step.props.validationSchema}
>
{formik => (
<Form>
<p>
Step {stepNumber + 1} of {totalSteps}
</p>
{step}
<div style={{ display: "flex" }}>
{stepNumber > 0 && (
<button onClick={() => previous(formik.values)} type="button">
Back
</button>
)}
<div>
<button disabled={formik.isSubmitting} type="submit">
{isLastStep ? "Submit" : "Next"}
</button>
</div>
</div>
</Form>
)}
</Formik>
);
};
const WizardStep = ({ children }) => children;
const Demo = () => {
const submitform=(values)=>{
alert('First name:'+values.firstName+' Last name:'+values.lastName+' Mobile:'+values.mobile+' Email:'+values.email);
}
return(
<>
<Wizard
initialValues={{
email: "",
firstName: "",
lastName: "",
mobile:''
}}
onSubmit={values => submitform(values)}
>
<WizardStep
validationSchema={Yup.object({
firstName: Yup.string().required("required"),
lastName: Yup.string().required("required")
})}
>
<div>
<label htmlFor="firstName">First Name</label>
<Field
autoComplete="given-name"
component="input"
id="firstName"
name="firstName"
placeholder="First Name"
type="text"
/>
<ErrorMessage className="error" component="div" name="firstName" />
</div>
<div>
<label htmlFor="lastName">Last Name</label>
<Field
autoComplete="family-name"
component="input"
id="lastName"
name="lastName"
placeholder="Last Name"
type="text"
/>
<ErrorMessage className="error" component="div" name="lastName" />
</div>
</WizardStep>
<WizardStep
validationSchema={Yup.object({
mobile: Yup.number('Invalid mobile').min(10,"Invalid mobile").required("required")
})}
>
<div>
<label htmlFor="mobile">Mobile</label>
<Field
autoComplete="mobile"
component="input"
id="mobile"
name="mobile"
placeholder="Mobile"
type="text"
/>
<ErrorMessage className="error" component="div" name="mobile" />
</div>
</WizardStep>
<WizardStep
validationSchema={Yup.object({
email: Yup.string()
.email("Invalid email address")
.required("required")
})}
>
<div>
<label htmlFor="email">Email</label>
<Field
autoComplete="email"
component="input"
id="email"
name="email"
placeholder="Email"
type="text"
/>
<ErrorMessage className="error" component="div" name="email" />
</div>
</WizardStep>
</Wizard>
</>
)
}
function App() {
return (
<div className="App">
<Demo />
</div>
);
}
export default App;

react-admin - Stop List's Filters from submitting "onChange"

Is there a way to have a List's filters not submit automatically on every field's change? I'm trying to implement a reporting resource and it would be ideal to have the user set the filters they want and then submit the form, to have the report generated, as they tend to be heavy on the DB.
Thanks!
React-admin's <Filter> component does not submit after every field change, because it uses a debouncing function to submit only once the user has stopped typing.
That being said, if you don't want the filter form to auto-submit, but prefer a filter form with an explicit submit button, you'll have to build a custom <Filter> component yourself - react-admin doesn't provide such a component.
Here is an example custom filter form:
import * as React from 'react';
import { Form } from 'react-final-form';
import { Box, Button, InputAdornment } from '#material-ui/core';
import SearchIcon from '#material-ui/icons/Search';
import { TextInput, NullableBooleanInput, useListContext } from 'react-admin';
const PostFilterForm = () => {
const {
displayedFilters,
filterValues,
setFilters,
hideFilter
} = useListContext();
if (!displayedFilters.main) return null;
const onSubmit = (values) => {
if (Object.keys(values).length > 0) {
setFilters(values);
} else {
hideFilter("main");
}
};
const resetFilter = () => {
setFilters({}, []);
};
return (
<div>
<Form onSubmit={onSubmit} initialValues={filterValues}>
{({ handleSubmit }) => (
<form onSubmit={handleSubmit}>
<Box display="flex" alignItems="flex-end" mb={1}>
<Box component="span" mr={2}>
{/* Full-text search filter. We don't use <SearchFilter> to force a large form input */}
<TextInput
resettable
helperText={false}
source="q"
label="Search"
InputProps={{
endAdornment: (
<InputAdornment>
<SearchIcon color="disabled" />
</InputAdornment>
)
}}
/>
</Box>
<Box component="span" mr={2}>
{/* Commentable filter */}
<NullableBooleanInput helperText={false} source="commentable" />
</Box>
<Box component="span" mr={2} mb={1.5}>
<Button variant="outlined" color="primary" type="submit">
Filter
</Button>
</Box>
<Box component="span" mb={1.5}>
<Button variant="outlined" onClick={resetFilter}>
Close
</Button>
</Box>
</Box>
</form>
)}
</Form>
</div>
);
};
This is documented at: https://marmelab.com/react-admin/List.html#building-a-custom-filter
Edit 2021-11-10: Added example and link to documentation