How to use Link and Route inside of condition term - javascript

So I am trying to move through pages in react, my goal is when I did validate the things I need (name, and number) the page will switch and I will be in another route. (without refresh the page).
I tried to do it with window.location but its refreshing the page
I cant use <Link> because I want to switch route only after the validation (inside IF condition) or I can and I don't know-how.
my code :
import React, {useState} from 'react'
import {Link} from 'react-router-dom';
export default function Signup(props) {
const [name, setName] = useState(' ')
const [number, setNumber] = useState(' ')
const [forklift, setForklift] = useState(false)
const [styleNumber,setStyleNumber]= useState({
display:'none',
})
const [styleName,setStyleName]= useState({
display:'none',
})
let validNum=false;
let validName=false;
let driverLicense=()=>{
if(forklift === 'true'){
setForklift(true)
}
else{
setForklift(false)
}
if(number.length<5 || number.length>5){
setStyleNumber({
display:'block',
color:'red'
})
}
else{
validNum=true;
}
if(name.indexOf(' ')==-1|| name.length<4){
setStyleName({
display:'block',
color:'red'
})
}
else{
validName=true;
}
if(validNum && validName){
props.addWorker(name,number,forklift)
let myBtn=document.getElementById('button').innerHTML=<Link to='/'></Link>
console.log(myBtn)
}
else{
alert('Error')
}
}
return (
<div>
<h2>Sign up</h2>
<label>No.</label>
<input onChange={(e)=>{setNumber(e.target.value)}} type='number' maxLength='5'></input><br />
<br /> <p style={styleNumber}> the number must be with 5 digits.</p>
<label>Full Name:</label> <input onChange={(e)=>{setName(e.target.value)}} ></input><br /> <br />
<p style={styleName} >the name must contain minimum 4 characters.</p>
<label>Forkligt truck</label> <br /> <br />
<input onClick={(e)=>{setForklift(e.target.value)}} type="radio" name='Forklift' value="true"/>
<label >Yes</label><br/>
<input onClick={(e)=>{setForklift(e.target.value)}} type="radio" name='Forklift' checked value="false"/>
<label >no</label><br /> <br />
<button id='button' onClick={driverLicense}>Create</button>
</div>
)
}

I think what you want to achieve is to Redirect the page when you meet a condition
in this case
import React, {useState} from 'react'
import {Redirect} from 'react-router-dom';
export default function Signup(props) {
const [name, setName] = useState(' ')
const [isVerified, setIsVerified = useState(false);
const [number, setNumber] = useState(' ')
const [forklift, setForklift] = useState(false)
const [styleNumber,setStyleNumber]= useState({
display:'none',
})
const [styleName,setStyleName]= useState({
display:'none',
})
let validNum=false;
let validName=false;
let driverLicense=()=>{
if(forklift === 'true'){
setForklift(true)
}
else{
setForklift(false)
}
if(number.length<5 || number.length>5){
setStyleNumber({
display:'block',
color:'red'
})
}
else{
validNum=true;
}
if(name.indexOf(' ')==-1|| name.length<4){
setStyleName({
display:'block',
color:'red'
})
}
else{
validName=true;
}
if(validNum && validName){
props.addWorker(name,number,forklift)
setIsVerified(true);
}
else{
alert('Error')
}
}
if (isVerified) {
return <Redirect to="/" />
}
return (
<div>
<h2>Sign up</h2>
<label>No.</label>
<input onChange={(e)=>{setNumber(e.target.value)}} type='number' maxLength='5'></input><br />
<br /> <p style={styleNumber}> the number must be with 5 digits.</p>
<label>Full Name:</label> <input onChange={(e)=>{setName(e.target.value)}} ></input><br /> <br />
<p style={styleName} >the name must contain minimum 4 characters.</p>
<label>Forkligt truck</label> <br /> <br />
<input onClick={(e)=>{setForklift(e.target.value)}} type="radio" name='Forklift' value="true"/>
<label >Yes</label><br/>
<input onClick={(e)=>{setForklift(e.target.value)}} type="radio" name='Forklift' checked value="false"/>
<label >no</label><br /> <br />
<button id='button' onClick={driverLicense}>Create</button>
</div>
)
}

This should work:
export default function Signup(props) {
const [redirect,setRedirect]=useState(false);
const[path,setPath]=useState("");
if(condition)
{
setPath(set your path here)
setRedirect(true);
}
return (
{redirect?<Redirect to={path}/>:null}
<div>
<h2>Sign up</h2>
<label>No.</label>
<input onChange={(e)=>{setNumber(e.target.value)}} type='number' maxLength='5'></input><br />
<br /> <p style={styleNumber}> the number must be with 5 digits.</p>
<label>Full Name:</label> <input onChange={(e)=>{setName(e.target.value)}} ></input><br /> <br />
<p style={styleName} >the name must contain minimum 4 characters.</p>
<label>Forkligt truck</label> <br /> <br />
<input onClick={(e)=>{setForklift(e.target.value)}} type="radio" name='Forklift' value="true"/>
<label >Yes</label><br/>
<input onClick={(e)=>{setForklift(e.target.value)}} type="radio" name='Forklift' checked value="false"/>
<label >no</label><br /> <br />
<button id='button' onClick={driverLicense}>Create</button>
</div>
)
}

The best way is to move pages without refreshing is by wrap your components with a higher-order component. Using HOC you can use context and change what you want to render. Refer documentation

Related

react state can not read property

I am facing an issue with react , it worked with individual usestates but when I made it as an object it failed , and this is the code :
import React, { useState } from 'react'
import {Link} from "react-router-dom"
import {DatabaseNetworkPoint} from '#icon-park/react';
import axios from "axios"
export default function Register() {
const [user, setUser] = useState({
username:"",
email:"",
password:"",
age:0,
gender:"",
})
const [file, setFile] = useState(null)
const handleChange = (event) => {
console.log(event.target.value)
setUser({
username:event.target.value,
email:event.target.value,
password:event.target.value,
age:event.target.value,
gender:event.target.value,
img:event.target.files[0]
})
setFile(event.target.files[0])
}
const handleSubmit = (event) => {
event.preventDefault()
console.log('button clicked', event.target)
}
return (
<div className='container'>
<div className='left'>
<div className='logo'>
<DatabaseNetworkPoint theme="outline" size="150" fill="#333"/>
<h1>WonderHit</h1>
</div>
<form className='form' onSubmit={handleSubmit}>
<input placeholder='Username' value={user.username} className='field' type="text" onChange={handleChange} />
<input placeholder='Email' value={user.email} className='field' type="email" onChange={handleChange} />
<input placeholder='Password' value={user.password} className='field' type="password" onChange={handleChange} />
<input placeholder='Age' value={user.age} className='field' name='age' type="number" onChange={handleChange} />
<input placeholder='Gender' value={user.gender} className='field' name='gender' type="text" onChange={handleChange} />
<div className='profilePic'>
<div className='Photo'></div>
<input className='field2' id='file' type="file" onChange={handleChange} />
<label htmlFor = "file" className='uploadPic' >+</label>
</div>
<button className='submit' type="submit">Register</button>
<h3 className='routing'>You already have an account ? <Link className='rot' to="/">Login</Link></h3>
</form>
</div>
<img className='right' src='https://images.unsplash.com/photo-1562577309-4932fdd64cd1?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1074&q=80' />
</div>
)
}
and this is the error Iam getting :
Uncaught TypeError: Cannot read properties of null (reading '0')
what might be the problem ?? is it the file thats causing me issues ? should I handle it as string ??????
img:event.target.files[0]
You're calling handleChange for every <input>, whether it's a file type or not.
Use a different handler, don't use the same handler(handleChange) for every input change, the issue is coming because of another field change file type input returning null.
Use another handler for the upload file and set it to use of useState and use it for a later use case.
It's because this line setFile(event.target.files[0]) you should first check existing of event.target.files then set it in your state;
event.target.files && setFile(event.target.files[0])
Maybe you can add a check to your handleChange(event)'s event, and make a conditional setting to your user state. Also remember using new object when setting user state, because you would like to save the other input's state in your user
const handleChange = (event) => {
if(event.target.placeholder === 'Username'){
// 📌 use {...user, [update]: event.target.value }
setUser({...user, username:event.target.value });
}
//else if (){ ...other input}
if(event.target.id = 'file'){
setFile(event.target.files[0])
}
}
a simple example:
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<div id="root"></div>
<script type="text/babel">
function App () {
const [user, setUser] = React.useState({});
const handleChange = (e) => {
if (e.target.placeholder === "Username") {
setUser({...user, username: e.target.value});
}
if (e.target.placeholder === "Email") {
setUser({...user, email: e.target.value});
}
if (e.target.placeholder === "Password") {
setUser({...user, password: e.target.value});
}
if (e.target.placeholder === "Age") {
setUser({...user, age: e.target.value});
}
if (e.target.placeholder === "Gender") {
setUser({...user, gender: e.target.value});
}
console.log(e.target);
if(e.target.id === "file"){
if (e.target.files) {
const img = document.getElementById("img");
console.log(img);
img.src = URL.createObjectURL(e.target.files[0]);
}
}
}
return <div>
<div>Inputs</div>
<input placeholder='Username' value={user.username} className='field' type="text" onChange={handleChange} />
<input placeholder='Email' value={user.email} className='field' type="email" onChange={handleChange} />
<input placeholder='Password' value={user.password} className='field' type="password" onChange={handleChange} />
<input placeholder='Age' value={user.age} className='field' name='age' type="number" onChange={handleChange} />
<input placeholder='Gender' value={user.gender} className='field' name='gender' type="text" onChange={handleChange} />
<div>file (only accept photo)</div>
<input id="file" type="file" accept="image/*" onChange={handleChange}></input>
<div>User Object's props</div>
<div>user.username: {user.username}</div>
<div>user.email: {user.email}</div>
<div>user.password: {user.password}</div>
<div>user.age: {user.age}</div>
<div>user.gender: {user.gender}</div>
<br />
<div>image display</div>
<img id="img"></img>
</div>
}
</script>
<script type="text/babel">
ReactDOM.render(
<App></App>
, document.getElementById("root"));
</script>

Why is my useState not working (error in console)?

I have react components:
WelcomePage.jsx
import { useState } from "react";
import SignUpPage from "./SignUpPage";
function WelcomePage() {
const [signUp, toSignUp] = useState(false);
function signUpClick() {
toSignUp(true);
}
return (
<div>
{signUp ? (
<SignUpPage isOpen={toSignUp} back={toSignUp} />
) : (
<div className="Welcome_page__container animate__animated animate__fadeIn">
<h1 className="Welcome_page__title">Welcome to Hotel Review </h1>
<h3 className="Welcome_page__subtitle">Sign in :</h3>
<div className="Welcome_page__wrapper">
<label className="Welcome_page__input-title" htmlFor="welcome_mail">
E-mail:
</label>
<input
value={inputEmail}
onInput={(e) => setInputEmail(e.target.value)}
className="Welcome_page__input"
id="welcome_mail"
type="email"
placeholder="Your e-mail..."
/>
<label className="Welcome_page__input-title" htmlFor="welcome_pass">
Password:
</label>
<input
value={inputPass}
onInput={(e) => setInputPass(e.target.value)}
className="Welcome_page__input"
id="welcome_pass"
type="password"
placeholder="Your password..."
/>
<button className="Welcome_page__btn" onClick={loginClick}>
Login
</button>
<button className="Welcome_page__btn" onClick={signUpClick}>
Sign Up
</button>
</div>
</div>
)}
</div>
);
}
export default WelcomePage;
SignUpPage.jsx
import { useState } from "react";
import { Hotels } from "./Hotels";
function SignUpPage(props) {
const { isOpen, back } = props;
const [isSignUp, setSignUp] = useState(false);
return (
<div>
{isSignUp ? (
<Hotels />
) : (
<div className="Welcome_page__container animate__animated animate__fadeIn">
<button onClick={back(false)}>Back...</button>
<h1 className="Welcome_page__title">Welcome to Hotel Review </h1>
<h3 className="Welcome_page__subtitle">Sign up :</h3>
<div className="Welcome_page__wrapper">
<label className="Welcome_page__input-title" htmlFor="welcome_mail">
E-mail:
</label>
<input
value={inputEmail}
onInput={(e) => setInputEmail(e.target.value)}
className="Welcome_page__input"
id="welcome_mail"
type="email"
placeholder="Your e-mail..."
/>
<label className="Welcome_page__input-title" htmlFor="welcome_pass">
Password:
</label>
<input
value={inputPass}
onInput={(e) => setInputPass(e.target.value)}
className="Welcome_page__input"
id="welcome_pass"
type="password"
placeholder="Your password..."
/>
<label
className="Welcome_page__input-title"
htmlFor="welcome_pass"
></label>
<input
value={inputPass2}
onInput={(e) => setInputPass2(e.target.value)}
className="Welcome_page__input"
id="welcome_pass_repeat"
type="password"
placeholder="Repeat password..."
/>
<button className="Welcome_page__btn_2">Sign Up</button>
</div>
</div>
)}
</div>
);
}
export default SignUpPage;
When I click on Back in the SignUpPage component I get an error -
It is necessary that after clicking on back there is a return to WelcomePage.jsx
Maybe I'm not using or passing useState in SignUpPage.jsx
I read about the error on the Internet, they say that you need to useEffect (), but I doubt that this is the problem ...
Here is the error:
<button onClick={back(false)}>Back...</button>
You are basically calling the back function immediately causing the WelcomePage component to update while rendering the SignUpPage component.
You should do this:
<button onClick={() => back(false)}>Back...</button>
By doing this you are going to execute the back function only when you click on the button

React Hook Form set checkbox to checked state

I am trying out React-Hook-form
The simple code for the checkbox is as below:
import React from 'react'
import { useForm } from 'react-hook-form'
export default function App() {
const {
register,
handleSubmit,
formState: { errors },
} = useForm()
const onSubmit = (data: any) => console.log(data)
console.log(errors)
return (
<div className='mx-auto justify-center p-32 flex'>
<form onSubmit={handleSubmit(onSubmit)}>
<div className='p-2'>
<label htmlFor=''>January</label>
<input
type='checkbox'
placeholder='January'
{...register('January', {})}
className='mx-3'
checked
/>
</div>
<div className='p-2'>
<label htmlFor=''>February</label>
<input
type='checkbox'
placeholder='February'
{...register('February', {})}
className='mx-3'
/>
</div>
<input type='submit' />
</form>
</div>
)
}
I can submit the form correctly but I have like the January checkbox to start off as a checked box but when I put 'checked' as shown in the code, I somehow could not 'uncheck' it.
I seem to be missing something and any help would be greatly appreciated.
The issue with passing checked is that it takes control away from useForm to manage the checkbox.
Imagine the function register() returns { checked: true/false, onChange: changeHandler }. So if we where to look at the attributes this produces the following.
<input
type='checkbox'
placeholder='January'
{...register('January', {})}
className='mx-3'
checked
/>
<input
type='checkbox'
placeholder='January'
{...{
checked: true/false,
onChange: changeHandler,
}}
className='mx-3'
checked
/>
<input
type='checkbox'
placeholder='January'
checked={true/false}
onChange={changeHandler}
className='mx-3'
checked
/>
Since checked is present twice, the latter will override the former. In this case your checked is last so it overrides the value that is managed by useForm.
Passing it before the register() call won't help you either, since your default value will be overwritten by a value managed by useForm and is therefore never used.
Now that I've cleared up why this issue happens let's move on to the solution.
useForm allows you to pass a default values when you initially call the hook.
const {
register,
handleSubmit,
formState: { errors },
} = useForm({ defaultValues: { January: true } });
// ...
<input
type='checkbox'
{...register("January")}
className='mx-3'
/>
Alternatively, instead of giving each checkbox its own name, you could also use "months". If there are multiple checkboxes using the same name, the result will not be true/false, but rather an array containing the values.
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
defaultValues: { months: ["January"] }
// only January ^ is checked by default
});
//...
<input
type='checkbox'
value='January'
{...register("months")}
className='mx-3'
/>
<input
type='checkbox'
value='February'
{...register("months")}
className='mx-3'
/>
The complete working code based on #3limin4tOr
import React, { useState } from 'react'
import { useForm } from 'react-hook-form'
export default function App() {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
defaultValues: { months: ['January'] },
})
const onSubmit = (data: any) => console.log(data)
console.log(errors)
return (
<div className='mx-auto justify-center p-32 flex'>
<form onSubmit={handleSubmit(onSubmit)}>
<div className='p-2'>
<label htmlFor=''>January</label>
<input
type='checkbox'
value='January'
placeholder='January'
{...register('months')}
className='mx-3'
/>
</div>
<div className='p-2'>
<label htmlFor=''>February</label>
<input
type='checkbox'
value='February'
placeholder='February'
{...register('months')}
className='mx-3'
/>
</div>
<input type='submit' />
</form>
</div>
)
}
You can find here input, checkbox, and radio in one field with React Hook form
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import "./App.css";
import { FormProvider, useForm, useFormContext } from "react-hook-form";
const ChooseCarType = () => {
const { register } = useFormContext();
return (
<>
<div>
<label htmlFor="field-rain">
<input
{...register("weather")}
type="radio"
value="rain"
id="field-rain"
/>
Rain
</label>
<label htmlFor="field-wind">
<input
{...register("weather")}
type="radio"
value="wind"
id="field-wind"
/>
Lots of wind
</label>
<label htmlFor="field-sun">
<input
{...register("weather")}
type="radio"
value="sun"
id="field-sun"
/>
Sunny
</label>
</div>
</>
);
};
const ChooseService = () => {
const { register } = useFormContext();
return (
<>
<div>
<label>
<input type="checkbox" {...register("jan")} />
Jan
</label>
<label>
<input type="checkbox" {...register("feb")} />
Feb
</label>
<label>
<input type="checkbox" {...register("mar")} />
Mar
</label>
</div>
</>
);
};
const UserData = () => {
const { register } = useFormContext();
return (
<>
<div>
<label>
Username
<input {...register("username")} />
</label>
<label>
Password
<input {...register("password")} />
</label>
</div>
</>
);
};
function App() {
const methods = useForm();
const onSubmit = (data: any) => alert(JSON.stringify(data, null, 2));
return (
<FormProvider {...methods}>
<form onSubmit={methods.handleSubmit(onSubmit)}>
<ChooseCarType />
<ChooseService />
<UserData />
<button type="submit">Submit</button>
</form>
</FormProvider>
);
}
export default App;

Radio button global state for name attribute

I need to be able to have radion buttons or checkboxes to show / hide content if its checked. There will be more radio buttons and checkboxes to show content in the same form, so to distinguish them from each other, it could be based on the name attribute.
So far i can show the hidden fields when i check the radio buttons, but i want one to cancel out the other, but only if it has the same name attribute (something else can also work).
Is there a react genius who can figure this out? I would be forever in your debt :)
class PartnerRoute extends Component {
constructor(props) {
super(props)
this.state = {
showOneTimeFee: '',
showSubscription: ''
};
}
toggleOneTimeFee = () => {
const currentState = this.state.showOneTimeFee;
this.setState({
showOneTimeFee: !currentState
})
}
toggleSubscription = () => {
const currentState = this.state.showSubscription;
this.setState({
showSubscription: !currentState
})
}
render() {
return (
<div className="partner-route">
<ContentContainer>
<div className="form--create-event">
<form>
<h3>Event information</h3>
<GridContainer columnCount="one">
<CustomInput type="text" placeholder="Event name" />
</GridContainer>
<GridContainer columnCount="one">
<CustomTextarea type="text" placeholder="Event description" />
</GridContainer>
<h3>Event date</h3>
<GridContainer columnCount="three">
<CustomInput type="text" placeholder="Day" />
<CustomInput type="text" placeholder="Month" />
<CustomInput type="text" placeholder="Year" />
</GridContainer>
<h3>Payment</h3>
<GridContainer columnCount="one">
<CustomRadio
type="radio"
name="payment"
id="rb1"
value="1"
label="Free, no payment needed"
/>
<CustomRadio
type="radio"
name="payment"
id="rb2"
value="2"
label="1 time fee"
onChange={this.toggleOneTimeFee}
/>
{this.state.showOneTimeFee &&
<div className="hidden-field">
<CustomInput type="text" placeholder="Price" />
</div>
}
<CustomRadio
type="radio"
name="payment"
id="rb3"
value="3"
label="Subscription"
onChange={this.toggleSubscription}
/>
{this.state.showSubscription &&
<div className="hidden-field">
<CustomInput type="text" placeholder="Price" />
</div>
}
</GridContainer>
</form>
</div>
</ContentContainer>
</div>
)
}
}
export default PartnerRoute
Please check this example where I used setState with prevState that is important and also I used changeHandler for all three radio. Moreover, to run this code in my side I changed all Custom input with generic input for ex CustomInput to input. Please revert this your side.
import React, {Component} from "react";
export default class PartnerRoute extends Component {
constructor(props) {
super(props);
this.state = {
showOneTimeFee: false,
showSubscription: false
};
}
handleChange = (event) => {
if (event.target.value == 2) // One Time Fee
this.setState(prevState => {
return {
showOneTimeFee: !prevState.showOneTimeFee,
showSubscription: false
};
});
else if (event.target.value == 3) // Subscription
this.setState(prevState => {
return {
showOneTimeFee: false,
showSubscription: !prevState.showSubscription
};
});
else // Free, no payment needed
this.setState({
showOneTimeFee: false,
showSubscription: false
});
};
render() {
return (
<div className="partner-route">
<div>
<div className="form--create-event">
<form>
<h3>Event information</h3>
<div>
<input type="text" placeholder="Event name"/>
</div>
<div>
<input type="text" multiline="true" placeholder="Event description"/>
</div>
<h3>Event date</h3>
<div>
<input type="text" placeholder="Day"/>
<input type="text" placeholder="Month"/>
<input type="text" placeholder="Year"/>
</div>
<h3>Payment</h3>
<div>
<input type="radio" name="payment" id="rb1" value="1" label="Free, no payment needed"
onChange={this.handleChange}/>
<label htmlFor="rb1">Free, no payment needed</label><br/>
<input type="radio" name="payment" id="rb2" value="2" label="1 time fee"
onChange={this.handleChange}/>
<label htmlFor="rb2">1 time fee</label><br/>
{this.state.showOneTimeFee &&
<div className="hidden-field">
<input type="text" placeholder="One Time Price"/>
</div>
}
<input type="radio" name="payment" id="rb3" value="3" label="Subscription"
onChange={this.handleChange}/>
<label htmlFor="rb3">Subscription</label><br/>
{this.state.showSubscription &&
<div className="hidden-field">
<input type="text" placeholder="Subscription Price"/>
</div>
}
</div>
</form>
</div>
</div>
</div>
)
}
}

Cannot read property 'value' of null in ReactJS

I've been trying to console.log these 2 inputs, but can't seem to figure it out, can anyone tell me what I've done wrong?
I keep getting the Cannot read property 'value' of null error
function printInputs() {
let username = document.getElementById('user').value
let password = document.getElementById('pass').value
console.log(username);
console.log(password);
}
function App() {
return (
<div className="App">
<h1>Log In</h1>
<h1>{code}</h1>
<form>
<input className='userInput' id='user' type='text' placeholder='username' /><br />
<input className='userInput' id='pass' type='password' placeholder='password' /><br />
<input className='userSubmit' type='submit' value='Log In' onSubmit={printInputs()} />
</form>
</div>
);
}
onSubmit={printInputs()}
You are trying to call printInputs immediately (before the render function has returned anything so before the inputs are in the page).
You need to pass a function to onSubmit:
onSubmit={printInputs}
That said, this is not the approach to take for getting data from forms in React. See the Forms section of the React guide for the right approach.
The way to write forms in react. Working example demo
function App() {
const [state, setState] = React.useState({ username: "", password: "" });
const handleSubmit = e => {
e.preventDefault();
console.log(state);
};
const handleChange = e => {
setState({
...state,
[e.target.name]: e.target.value
});
};
return (
<div className="App">
<h1>Log In</h1>
<form onSubmit={handleSubmit}>
<input
className="userInput"
name="username"
type="text"
placeholder="username"
onChange={handleChange}
/>
<br />
<input
className="userInput"
name="password"
type="password"
placeholder="password"
onChange={handleChange}
/>
<br />
<input className="userSubmit" type="submit" value="Log In" />
</form>
</div>
);
}
in the first never use real dom to manipulate the dom in
React ,use a state to get de value and the onSumbit is used in Form tag
import React, { useState } from "React";
const App = () => {
const [userName, setUserName] = useState("");
const [password, setPassword] = useState("");
const printInputs = () => {
console.log(userName);
console.log(password);
};
return (
<div className="App">
<h1>Log In</h1>
<form onSubmit={printInputs}>
<input
className="userInput"
id="user"
type="text"
placeholder="username"
onChange={event => setUserName(event.target.value)}
/>
<br />
<input
className="userInput"
id="pass"
type="password"
placeholder="password"
onChange={event => setPassword(event.target.value)}
/>
<br />
<input
className="userSubmit"
type="submit"
value="Log In"/>
</form>
</div>
);
};
export default App;

Categories

Resources