I wanted to create a form with text field, age, country and gender. however there seems to be a problem. The age and gender field seems to be overlapping on each other. How do I make every input field be in it's own row instead of overlapping
codesandbox, the problem seems to be there only when you open the website in full
import React, { Fragment, useState } from "react";
import { Container, Row, Col, Form } from "react-bootstrap";
import {
CountryDropdown,
RegionDropdown,
CountryRegionData
} from "react-country-region-selector";
const App = () => {
const [age, setAge] = useState("");
const [gender, setGender] = useState("");
const [country, setCountry] = useState("");
const [text, setText] = useState("");
const handleSubmit = async () => {
console.log(age, gender, country, text);
};
return (
<Fragment>
<Container>
<Row md={4}>
<Col xs={12} md={7}>
<Form.Group controlId="textarea">
<Form.Label />
<Form.Control
as="textarea"
rows="20"
onChange={e => setText(e.target.value)}
placeholder="Enter you text"
/>
</Form.Group>
</Col>
<Col xs={12} md={5}>
<Form className="mb-3">
<Form.Row>
<Form.Group as={Row}>
<Form.Label>
Age
<Form.Control
type="text"
name="age"
value={age}
onChange={e => setAge(e.target.value)}
required
/>
</Form.Label>
</Form.Group>
<br />
<Form.Group controlId="exampleForm.SelectCustomSizeSm" as={Row}>
<Form.Label>Gender</Form.Label>
<Form.Control
as="select"
size="sm"
custom
value={gender}
onChange={e => setGender(e.target.value)}
>
<option>Male</option>
<option>Female</option>
<option>Prefer Not To Say</option>
</Form.Control>
</Form.Group>
<Form.Group>
<Form.Label>
Country
<CountryDropdown
value={country}
onChange={e => setCountry(e)}
/>
</Form.Label>
</Form.Group>
</Form.Row>
</Form>
<Form.Group as={Col}>
<input
type="submit"
className="btn btn-dark my-1"
value="Submit"
onClick={handleSubmit}
/>
</Form.Group>
</Col>
</Row>
</Container>
</Fragment>
);
};
export default App;
You need to first remove the as={Row} attributes from both the Age and Gender form group as its not the use case for what you are trying to achieve. The <Form.Label> of the age form group component is not used properly.
After making those changes it worked fine. Here is a snippet
import React, { Fragment, useState } from "react";
import { Container, Row, Col, Form } from "react-bootstrap";
import {
CountryDropdown,
RegionDropdown,
CountryRegionData
} from "react-country-region-selector";
const App = () => {
const [age, setAge] = useState("");
const [gender, setGender] = useState("");
const [country, setCountry] = useState("");
const [text, setText] = useState("");
const handleSubmit = async () => {
console.log(age, gender, country, text);
};
return (
<Fragment>
<Container>
<Row md={4}>
<Col xs={12} md={7}>
<Form.Group controlId="textarea">
<Form.Label />
<Form.Control
as="textarea"
rows="20"
onChange={e => setText(e.target.value)}
placeholder="Enter you text"
/>
</Form.Group>
</Col>
<Col xs={12} md={5}>
<Form className="mb-3">
<Form.Row>
<Form.Group>
<Form.Label>
Age
</Form.Label>
<Form.Control
type="text"
name="age"
value={age}
onChange={e => setAge(e.target.value)}
required
/>
</Form.Group>
<br />
<Form.Group controlId="exampleForm.SelectCustomSizeSm">
<Form.Label>Gender</Form.Label>
<Form.Control
as="select"
size="sm"
custom
value={gender}
onChange={e => setGender(e.target.value)}
>
<option>Male</option>
<option>Female</option>
<option>Prefer Not To Say</option>
</Form.Control>
</Form.Group>
<Form.Group>
<Form.Label>
Country
<CountryDropdown
value={country}
onChange={e => setCountry(e)}
/>
</Form.Label>
</Form.Group>
</Form.Row>
</Form>
<Form.Group as={Col}>
<input
type="submit"
className="btn btn-dark my-1"
value="Submit"
onClick={handleSubmit}
/>
</Form.Group>
</Col>
</Row>
</Container>
</Fragment>
);
};
export default App;
The easiest solution is to remove as={Row} from <Form.Group as={Row}>.
<Container>
<Row md={4}>
<Col xs={12} md={7}>
{/* ... */}
</Col>
<Col xs={12} md={5}>
<Form className="mb-3">
<Form.Row>
{/* <Form.Group as={Row}> */}
<Form.Group>
<Form.Label>
Age
<Form.Control type="text" name="age" required />
</Form.Label>
</Form.Group>
<br />
{/* <Form.Group controlId="exampleForm.SelectCustomSizeSm" as={Row}> */}
<Form.Group controlId="exampleForm.SelectCustomSizeSm">
<Form.Label>Gender</Form.Label>
<Form.Control as="select" size="sm" custom>
<option>Male</option>
<option>Female</option>
<option>Prefer Not To Say</option>
</Form.Control>
</Form.Group>
<Form.Group>{/* ... */}</Form.Group>
</Form.Row>
</Form>
<Form.Group as={Col}>{/* ... */}</Form.Group>
</Col>
</Row>
</Container>
Alternatively, you can remove <Form.Row /> entirely. The solution you choose depends on the layout you expect.
Related
<Field
className="col ml-1 pl-1 pr-0 form-control"
type="number"
min="0"
max="100"
id={`itemsAndServices[${index}].percentage`}
name={`itemsAndServices[${index}].percentage`}
/>
This restraint of min and max doesn't seem to work. Is this something that is supported or do I have to use the original input
You could use Yup for validation in Formik. Here is the example:
import React from 'react';
import { Formik, Form, Field } from 'formik';
import * as Yup from 'yup';
const SignupSchema = Yup.object().shape({
firstName: Yup.string()
.min(2, 'Too Short!')
.max(50, 'Too Long!')
.required('Required'),
lastName: Yup.string()
.min(2, 'Too Short!')
.max(50, 'Too Long!')
.required('Required'),
email: Yup.string().email('Invalid email').required('Required'),
});
export const ValidationSchemaExample = () => (
<div>
<h1>Signup</h1>
<Formik
initialValues={{
firstName: '',
lastName: '',
email: '',
}}
validationSchema={SignupSchema}
onSubmit={values => {
// same shape as initial values
console.log(values);
}}
>
{({ errors, touched }) => (
<Form>
<Field name="firstName" />
{errors.firstName && touched.firstName ? (
<div>{errors.firstName}</div>
) : null}
<Field name="lastName" />
{errors.lastName && touched.lastName ? (
<div>{errors.lastName}</div>
) : null}
<Field name="email" type="email" />
{errors.email && touched.email ? <div>{errors.email}</div> : null}
<button type="submit">Submit</button>
</Form>
)}
</Formik>
</div>
);
You could also use validate prop of the Field component Refer to the docs.
this is the signin code
import * as React from 'react';
import Avatar from '#mui/material/Avatar';
import Button from '#mui/material/Button';
import CssBaseline from '#mui/material/CssBaseline';
import TextField from '#mui/material/TextField';
import FormControlLabel from '#mui/material/FormControlLabel';
import Checkbox from '#mui/material/Checkbox';
import Link from '#mui/material/Link';
import Grid from '#mui/material/Grid';
import Box from '#mui/material/Box';
import LockOutlinedIcon from '#mui/icons-material/LockOutlined';
import Typography from '#mui/material/Typography';
import Container from '#mui/material/Container';
import { createTheme, ThemeProvider } from '#mui/material/styles';
const theme = createTheme();
export default function SignIn() {
const handleSubmit = (event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
// eslint-disable-next-line no-console
console.log({
email: data.get('email'),
password: data.get('password'),
});
};
return (
<ThemeProvider theme={theme}>
<Container component="main" maxWidth="xs">
<CssBaseline />
<Box
sx={{
marginTop: 8,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
}}
>
<Avatar sx={{ m: 1, bgcolor: 'secondary.main' }}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}>
<TextField
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
/>
<TextField
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="Remember me"
/>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
>
Sign In
</Button>
<Grid container>
<Grid item xs>
<Link href="#" variant="body2">
Forgot password?
</Link>
</Grid>
<Grid item>
<Link href="#" variant="body2">
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</Box>
</Box>
</Container>
</ThemeProvider>
);
}
this the signup code
import * as React from 'react';
import Avatar from '#mui/material/Avatar';
import Button from '#mui/material/Button';
import CssBaseline from '#mui/material/CssBaseline';
import TextField from '#mui/material/TextField';
import Link from '#mui/material/Link';
import Grid from '#mui/material/Grid';
import Box from '#mui/material/Box';
import LockOutlinedIcon from '#mui/icons-material/LockOutlined';
import Typography from '#mui/material/Typography';
import Container from '#mui/material/Container';
import { createTheme, ThemeProvider } from '#mui/material/styles';
const theme = createTheme();
export default function SignUp() {
const handleSubmit = (event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
// eslint-disable-next-line no-console
console.log({
email: data.get('email'),
password: data.get('password'),
});
};
return (
<ThemeProvider theme={theme}>
<Container component="main" maxWidth="xs">
<CssBaseline />
<Box
sx={{
marginTop: 8,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
}}
>
<Avatar sx={{ m: 1, bgcolor: 'secondary.main' }}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign up
</Typography>
<Box component="form" noValidate onSubmit={handleSubmit} sx={{ mt: 3 }}>
<Grid container spacing={2}>
<Grid item xs={12} sm={6}>
<TextField
autoComplete="given-name"
name="firstName"
required
fullWidth
id="firstName"
label="First Name"
autoFocus
/>
</Grid>
<Grid item xs={12} sm={6}>
<TextField
required
fullWidth
id="lastName"
label="Last Name"
name="lastName"
autoComplete="family-name"
/>
</Grid>
<Grid item xs={12}>
<TextField
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
/>
</Grid>
<Grid item xs={12}>
<TextField
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="new-password"
/>
</Grid>
</Grid>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
>
Sign Up
</Button>
<Grid container justifyContent="flex-end">
<Grid item>
<Link href="#" variant="body2">
Already have an account? Sign in
</Link>
</Grid>
</Grid>
</Box>
</Box>
</Container>
</ThemeProvider>
);
}
this the app.js
import React from 'react';
import ReactDOM from 'react-dom';
import SignUp from './containers/SignUp'
import {BrowserRouter as Router,Route} from 'react-router-dom'
import SignIn from './containers/SignIn';
import Home from "./containers/Home"
export default function App(){
return(
<Router>
<div>
<Route path="/"> <Home/> </Route>
<Route path="/signin"> <SignIn/> </Route>
<Route path="/signup"> <SignUp/> </Route>
</div>
</Router>
)
}
there is also a home.js i am sure it doesn't have any errors.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import SignUp from './containers/SignUp'
import SignIn from './containers/SignIn'
ReactDOM.render(
<React.StrictMode>
<App/>
</React.StrictMode>,
document.getElementById('root')
);
when I run this code it renders nothing . and also doesnt show any errors. please help me.
I have tried the above code . It shows no error. when I try to render a component without using routes it works perfectly fine.
The Route component API changed significantly in react-router-dom#6. The Route components are necessarily rendered directly by the Routes component and the routed components are rendered exclusively in the element prop.
Example:
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import SignUp from './containers/SignUp';
import SignIn from './containers/SignIn';
import Home from './containers/Home';
export default function App() {
return(
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/signin" element={<SignIn />} />
<Route path="/signup" element={<SignUp />} />
</Routes>
</Router>
);
}
I'm using Reactjs and Material UI and then Formik for the form validation. Whenever I finish completing the form and then hit the submit button, it looks as if it's making the request to post the data to the back-end, but then it reload back to the same form page.
const initialValues = {
from: "",
to: "",
purpose: "",
date: "",
kilometer: "",
amount: "",
claimType: "",
fullname:"",
vehicleNo: "",
bank: "",
email: "",
department: "",
status:"",
};
useEffect(() => {
if(!localStorage.getItem("accessToken")){
history.push("/");
}
}, [])
const validationSchema = Yup.object().shape({
from: Yup.string().required(),
to: Yup.string().required() ,
purpose:Yup.string().required(),
date:Yup.date().required(),
kilometer:Yup.number().required(),
amount: Yup.number().required(),
claimType: Yup.string().required(),
fullname: Yup.string().required(),
vehicleNo: Yup.string().required(),
department: Yup.string().required(),
bank: Yup.string().required(),
email: Yup.string().email(),
status: Yup.string(),
});
const onSubmit = (data)=> {
axios
.post("http://localhost:5001/dutyMileage", data, {
headers:
{ accessToken: localStorage.getItem("accessToken")},
})
.then((response) => {
console.log("it worked");
history.push('/Home');
})
}
return (
<div>
<Formik
initialValues={initialValues}
onSubmit={onSubmit}
validationSchema={validationSchema} >
<form className={classes.root} onSubmit={() => { alert("Claim Submitted"); }}>
<div className="formstep1">
<div>
<TextField
label="Full Name"
required
autoComplete="off"
variant="outlined"
name="fullname"
placeholder="Enter your Full name"
/>
<TextField
label="Department"
required
autoComplete="off"
variant="outlined"
name="department"
placeholder="Enter your department"
/>
</div>
<div>
<TextField
label="Bank"
required
autoComplete="off"
variant="outlined"
name="bank"
placeholder="Enter your bank name"
/>
<TextField
label="Date"
name="date"
variant="outlined"
/>
</div>
<div>
<TextField
disabled
variant="outlined"
label="status"
name="status"
value="PENDING"
/>
<TextField
label="Email"
required
autoComplete="off"
variant="outlined"
name="email"
placeholder="Enter your Email "
/>
</div>
<div className="select">
<InputLabel id="demo-simple-select-outlined-label">Claim Type</InputLabel>
<Select
required
name="claimType"
variant="outlined"
label="Claim Type"
value={claimType}
onChange={handleChange}
>
<MenuItem value="Duty Mileage">Duty Mileage</MenuItem>
<MenuItem value="Travelling Allowances">Travelling Allowances</MenuItem>
<MenuItem value="Approved Purchases">Approved Purchases</MenuItem>
<MenuItem value="Guest Of University">Guest Of University </MenuItem>
<MenuItem value="Other Claims">Other Claims</MenuItem>
</Select>
</div>
<div>
<TextField
label="Kilometer"
name="kilometer"
className={classes.root, classes.textField}
InputProps={{
endAdornment: <InputAdornment position="end">Km</InputAdornment>,
}}
variant="outlined"
onChange={ (event) => {
setKilometer(event.target.value);
}}
placeholder="Number of Kilometers"
/>
<TextField
label="Amount"
onChange={handleChangee}
name="amount"
InputProps={{
inputComponent: NumberFormatCustom,
}}
variant="outlined"
placeholder="Enter Amount In Naira"
/>
</div>
<div>
<TextField
label="From"
required
autoComplete="off"
variant="outlined"
placeholder="Journey From"
name="from" />
<TextField
label="To"
required
autoComplete="off"
variant="outlined"
name="to"
placeholder="journey To"
/>
</div>
<div>
<TextField
label="Vehicle Number"
required
autoComplete="off"
variant="outlined"
name="vehicleNo"
placeholder="Enter your Vehicle Number"
/>
<TextField
label="Purpose"
required
autoComplete="off"
variant="outlined"
name="purpose"
placeholder="purpose"
/>
</div>
</div>
<button type="submit"> Submit Claim</button>
</form>
</Formik>
</Paper>
</div>
);
}
And the back end goes like this
The router request:
const express = require("express");
const router = express.Router();
const { DutyMileage } = require("../models");
const { validateToken } = require("../middlewares/AuthMiddleware");
router.post("/", validateToken, async(req, res) => {
const post = req.body;
post.userId = req.username.userId;
post.StaffId = req.username.id;
await DutyMileage.create(post);
res.json(post);
});
Anytime I make request to submit the data to the database, it keeps reloading and it's stuck on the form page.
First, you must have errors in console, check inspection in browser and your node(npm console) errors
Second, here is code from formik official lib, try to remake you template for this to test:
<Formik
initialValues={{yourInitialValues}}
validationSchema={yourYupValidation}
onSubmit={(values, {setSubmitting, resetForm}) => {
// When button submits form and form is in the process of submitting, submit button is disabled
setSubmitting(true);
// Simulate submitting to database, shows us values submitted, resets form
setTimeout(() => {
//your code to send to API
//you can debug and test values here
alert(JSON.stringify(values, null, 2))
setSubmitting(false);
}, 1);
}}
>
{( {values,
errors,
touched,
handleChange,
handleBlur,
handleReset,
setFieldValue,
handleSubmit,
setFieldTouched,
isSubmitting }) => (
//use only formik functions to test
<form onSubmit={handleSubmit}>
</form>
)}
</Formik>
And last one: you have onSubmit={() => { alert("Claim Submitted"); }}, just check this line, you just console log onSubmit. Also your onSubmit const is outside Formik component, it may affect formik behaviour.
I have fields of auto-completion. When I press a button I want to clear the existing data and get clean fields.
I did this and it does not work:
<Autocomplete
id="combo-box-demo"
value={searchCases.NAME}
options={Cases}
getOptionLabel={(option) => option.NAME.toString()}
style={{ width: 200 }}
renderInput={(params) => (
<TextField {...params} label="name" variant="outlined" />
)}
onChange={(e) => onChange(e.target.innerText, "L_C_NUM")}
/>
<Autocomplete
id="combo-box-demo"
value={searchCases.AGE}
options={Cases}
getOptionLabel={(option) => option.AGE.toString()}
style={{ width: 200 }}
renderInput={(params) => (
<TextField {...params} label="age" variant="outlined" />
)}
onChange={(e) => onChange(e.target.innerText, "AGE")}
/>
That's the clean button
<Button onClick={() => handleReset()}>נקה נתונים</Button>
And that's the function:
const handleReset = () => {
setSearchCases({});
};
useEffect(()=>{
console.log(searchCases);
},[searchCases])
I am trying to implement a check box for the full consent of membership registration.
const [agree1, setAgree1] = useState(false); //agree1
const [agree2, setAgree2] = useState(false); //agree2
const [agree3, setAgree3] = useState(false); //agree3
const [total, settotal] = useState(false); // all agree
const buttonState = useCallback(() => {
if((agree1===true)&&(agree2===true)&&(agree3===true)){
settotal(true);
setDisabled('');
}
else {
setDisabled('disabled');
}
},[agree1,agree2,agree3,total]);
const totalchange = () => {
if(total ===true) { //전체동의가 true라면 다시 클릭 했을때 전부 unchecked
settotal(!total);
setAgree1(!agree1);
setAgree2(!agree2);
setAgree3(!agree3);
} else{ //그외(하나만 체크되 있거나 아무것도 없다면) 전부 checked로 만듬
settotal(true);
setAgree1(true);
setAgree2(true);
setAgree3(true);
// setDisabled('');
}
}
<div>
<div>
<input type="checkbox" name="total_agree" value="total_agree" checked={total} onChange={totalchange} />
<label>전체 동의</label>
</div>
<div>
<input type="checkbox" name="agree1" value="agree1" checked={agree1} onChange={changeState1} />
<label>회원 약관</label>
<span>전체보기</span>
</div>
<div>
<input type="checkbox" name="agree2" value="agree2" checked={agree2} onChange={changeState2} />
<label>개인정보 수집 및 이용</label>
<span>전체보기</span>
</div>
<div>
<input type="checkbox" name="agree3" value="agree3" checked={agree3} onChange={changeState3} />
<label>위치 정보 이용 동의</label>
<span>전체보기</span>
</div>
</div>
<br/>
입력해주신 이메일 정보는 회원가입 시 이메일로 설정됩니다.
<br/>
<div>
<label>이메일</label>
<input type = "email" onChange = {EmailHandler}/>
<button name="button" onClick = {clickFunction}>인증코드 발송</button>
</div>
If you activate the full terms and conditions, all the checkboxes below will be activated.
If you deactivate all terms and conditions, all the checkboxes below will also be deactivated.
Individually, all checkboxes should be enabled.
If you activate all checkboxes individually, the entire terms and conditions will also be activated.
If any of the checkboxes below are deactivated, the entire terms and conditions are deactivated.
When the entire terms and conditions are activated, the member sign-up button is activated.
I tried several methods, but failed to activate the button.
How can I implement it?
Please help...
Essentially what you need to do here is remove the states for total and disabled as they can be derived from the state of the other checkboxes.
The checkbox for "total" is checked if and only if all three are checked. When it is checked or unchecked, we handle that by setting the state of the other three.
Code Sandbox Demo
const Form = ({ onSubmit }) => {
const [agree1, setAgree1] = useState(false);
const [agree2, setAgree2] = useState(false);
const [agree3, setAgree3] = useState(false);
const isAgreedAll = agree1 && agree2 && agree3;
const handleCheckAll = (e) => {
setAgree1(e.target.checked);
setAgree2(e.target.checked);
setAgree3(e.target.checked);
};
const [email, setEmail] = useState("");
// placeholder so that you can implement your own validation
const emailLooksValid = email.length > 5;
const isDisabled = !isAgreedAll || !emailLooksValid;
return (
<>
<div>
<div>
<input
type="checkbox"
name="total_agree"
value="total_agree"
checked={isAgreedAll}
onChange={handleCheckAll}
/>
<label>전체 동의</label>
</div>
<div>
<input
type="checkbox"
name="agree1"
value="agree1"
checked={agree1}
onChange={(e) => setAgree1(e.target.checked)}
/>
<label>회원 약관</label>
<span>전체보기</span>
</div>
<div>
<input
type="checkbox"
name="agree2"
value="agree2"
checked={agree2}
onChange={(e) => setAgree2(e.target.checked)}
/>
<label>개인정보 수집 및 이용</label>
<span>전체보기</span>
</div>
<div>
<input
type="checkbox"
name="agree3"
value="agree3"
checked={agree3}
onChange={(e) => setAgree3(e.target.checked)}
/>
<label>위치 정보 이용 동의</label>
<span>전체보기</span>
</div>
</div>
<br />
입력해주신 이메일 정보는 회원가입 시 이메일로 설정됩니다.
<br />
<div>
<label>이메일</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<button
disabled={isDisabled}
name="button"
onClick={onSubmit(email)}
>
인증코드 발송
</button>
</div>
</>
);
};
export default Form;
If you want to, you could combine some of the logic for the three checkboxes into a renderCheckbox function.
If you don't want/need button visible prior to being active I like to use && for display. ex:
( isFlag1 && isFlag2 && isFlag3 && <button>Active Now</button>)