Radio buttons with react-hook-form - reactjs

I created a form with react-hook-form. It logs "fullName" and "city" correctly in the console, but not the radio buttons. With the radio buttons you get as result "null".
My code is as follows.
import React from 'react'
import './App.css';
import {useForm} from "react-hook-form";
function App() {
const {register, handleSubmit} = useForm();
function onSubmitButton(data) {
console.log(data)
}
return (
<>
<h1>Order weather</h1>
<form onSubmit={handleSubmit(onSubmitButton)}>
<input
{...register("fullName")}
type="text"
name="fullName"
placeholder="Name and surname"
id="name"
/>
<input
{...register("city")}
type="text"
name="city"
placeholder="City"
id="city"
/>
<p>I would like to:</p>
<label htmlFor="field-rain">
<input
{...register("rain")}
type="radio"
name="weather"
value="rain"
id="field-rain"
/>
Rain
</label>
<label htmlFor="field-wind">
<input
{...register("wind")}
type="radio"
name="weather"
value="wind"
id="field-wind"
/>
Lots of wind
</label>
<label htmlFor="field-sun">
<input
{...register("sun")}
type="radio"
name="weather"
value="sun"
id="field-sun"
/>
Sunny
</label>
<button type="submit">
Send
</button>
</form>
</>
);
}
export default App;
When I turn off name= "weather" and I check the buttons it does put it in the console, but it is not supposed to allow me to check all the buttons at the same time. Anyone have an idea how I can make sure I can get what is checked into the console?

Since rain, wind, sun should be assign to the same value we need to pass same params to register function as below
function App() {
const {register, handleSubmit} = useForm();
function onSubmitButton(data) {
console.log(data)
}
return (
<>
<h1>Order weather</h1>
<form onSubmit={handleSubmit(onSubmitButton)}>
<input
{...register("fullName")}
type="text"
placeholder="Name and surname"
id="name"
/>
<input
{...register("city")}
type="text"
placeholder="City"
id="city"
/>
<p>I would like to:</p>
<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>
<button type="submit">
Send
</button>
</form>
</>
);
}
export default App;
I hope this will fix the issue.

Related

handleSubmit not working when I try to use the function

I am getting an error in my code of handleSubmit function because ,here I am using this syntax 'export const Register = ()',so what needs to be fixed in my code so that I;m able to use the handleSubmit function I'll paste the code down below it keeps saying its not defined ive tried adding function handleSubmit() and const handleSubmit = () but its still not working any help on how to resolve this error please as i've tried for hours now i'm new to react and wondering as how i would be able to resolve this error
export const Register = () => {
handleSubmit = e => {
e.preventDefault();
console.log('works!');
};
return (
<form onSubmit={this.handleSubmit} >
<h3>Sign Up</h3>
<div className="form-group">
<label> First Name</label>
<input type="text" className="form-control" placeholder="First Name" />
</div>
<div className="form-group">
<label> Last Name</label>
<input type="text" className="form-control" placeholder="Last Name" />
</div>
<div className="form-group">
<label> Email</label>
<input type="email" className="form-control" placeholder="Email" />
</div>
<div className="form-group">
<label> Password</label>
<input type="password" className="form-control" placeholder="Password" />
</div>`
<div className="form-group">
<label> Confirm Password</label>
<input type="password" className="form-control" placeholder="Confirm Password" />
</div>`
<button className="btn btn-primary btn-block" > Sign Up</button>
</form >
);
}
export default Register;
When using the arrow function syntax, the function has to be declared with const. Make it like this:
const handleSubmit = e => {
e.preventDefault();
console.log('works!');
};
Also, you only need to export the Register component once. Using export default Register at the end is sufficient.
And we don't use this in a function component, it is just hadleSubmit:
<form onSubmit={handleSubmit} >
<h3>Sign Up</h3>
<div className="form-group">
<label> First Name</label>
<input type="text" className="form-control" placeholder="First Name" />
</div>
<div className="form-group">
<label> Last Name</label>
<input type="text" className="form-control" placeholder="Last Name" />
</div>
<div className="form-group">
<label> Email</label>
<input type="email" className="form-control" placeholder="Email" />
</div>
<div className="form-group">
<label> Password</label>
<input type="password" className="form-control" placeholder="Password" />
</div>`
<div className="form-group">
<label> Confirm Password</label>
<input type="password" className="form-control" placeholder="Confirm Password" />
</div>`
<button className="btn btn-primary btn-block" > Sign Up</button>
</form >

How to call a function in a Reusable component in React

Hi I am working on a React project in my project one button is coming soo many times. So I created one component for Button and I am reusing that component where ever I get a button. Now the problem is when I am trying to apply onClick function to that Button component, my function is not working so please help me to resolve this issue.
This is Button Component Button.js
import React from "react";
import "./Button.css";
const Button = () => {
return (
<div>
<button className="btn btn-primary">Show login button</button>
</div>
);
};
export default Button;
This is Button.css, I have written nothing in this
This is App.js
import React, { useState } from "react";
import Button from "./Button/Button";
import "./App.css";
const App = () => {
const [hideForm, setHideForm] = useState(false);
const showLoginForm = () => {
setHideForm(true);
};
return (
<div className="container">
<div className="row justify-content-center">
<div className="col-4">
{hideForm ? (
<div className="loginform">
<form>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
type="email"
className="form-control"
id="email"
placeholder="Enter email"
></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
className="form-control"
id="password"
placeholder="Enter password"
></input>
</div>
<button type="submit" className="btn btn-primary mt-3">
Submit
</button>
</form>
</div>
) : (
<div className="signupform">
<form>
<div className="form-group">
<label htmlFor="firstname">Firstname</label>
<input
type="text"
className="form-control"
id="firstname"
placeholder="Enter firstname"
></input>
</div>
<div className="form-group">
<label htmlFor="lastname">Lastname</label>
<input
type="text"
className="form-control"
id="lastname"
placeholder="Enter lastname"
></input>
</div>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
type="email"
className="form-control"
id="email"
placeholder="Enter email"
></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
className="form-control"
id="password"
placeholder="Enter password"
></input>
</div>
<button type="submit" className="btn btn-primary mt-3">
Submit
</button>
</form>
</div>
)}
<div className="buttons mt-3">
<Button onClick={() => showLoginForm()}></Button>
</div>
</div>
</div>
</div>
);
};
export default App;
const Button = ({handleClick}) => {
return (
<div>
<button onClick={handleClick} className='btn btn-primary'>Show login button</button>
</div>
)
}
Use It like this:
<Button handleClick={()=>anyFunc()}/>
or
<Button handleclick={anyFunc}/>
``
You can pass the Parent's on click event to child as a props and when you click on the child component's button event that is being declared on the parent's component can be called. Here is how you can do it:
Code on the Parent Component:
const myClick =()=>{
// on click will be called here when button will be pressed
}
<Button onClick={this.myClick}></Button>
Code on the Child Component:
<button onClick={this.props.myClick}>Click Here</button>

Changing state on route change in React

I want to show a select tag when a checkbox is checked.
In "/register" route (which is the default route), checkbox should be unchecked by default and in "/register/tradeUser", checkbox should be checked by default.
If I use defaultChecked="true", the state of checked will not change to true.
So I want to know, how can I call setChecked(true) inside the conditional rendering?
const Register = (match) => {
const [checked, setChecked] = useState(false);
const toggleChecked = () => {
if (checked) {
setChecked(false);
} else {
setChecked(true);
}
};
return (
<form>
<input type="text" name="first-name" placeholder="First Name" />
<input type="text" name="last-name" placeholder="Last Name" />
<input type="email" name="email" placeholder="Email Address" />
<input type="password" name="password" placeholder="Password" />
<input type="password" name="confirm" placeholder="Confirm Password" />
{match.location.pathname === "/register/tradeUser" ? (
<div>
<label>
<input
type="checkbox"
name="profession"
checked={checked}
onChange={() => toggleChecked()}
/>
I am an Architect/Interior designer
</label>
<select
name="info"
placeholder="Select Option to add Architect Info"
className={`${checked ? "" : "hidden"}`}
>
<option value="certi-number">Certificate Number</option>
<option value="certificate">Registration Certificate</option>
</select>
</div>
) : (
<div>
<label>
<input
type="checkbox"
name="profession"
checked={checked}
onChange={() => toggleChecked()}
/>
I am an Architect/Interior designer
</label>
<select
name="info"
placeholder="Select Option to add Architect Info"
className={`${checked ? "" : "hidden"}`}
>
<option value="certi-number">Certificate Number</option>
<option value="certificate">Registration Certificate</option>
</select>
</div>
)}
<button>Register</button>
</form>
<label>
Existing User?
<Link to="/login" className="link">
{" Login "}
</Link>
</label>
</div>
);
};
you can easily run function in jsx like this
export default function App() {
return (
<div className="App">
{console.log(1)}
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
however you shouldn't set state in jsx because it will loop infinitely
in this case you can use useEffect
useEffect(()=>{
if(match.location.pathname=== "/register/tradeUser"){
setChecked(true)
}else{
setChecked(false)
}
},[match.location.pathname])

Error: input is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`

import React , { Component } from 'react'
class Login extends Component{
constructor(props){
super(props)
}
render(){
return(
<form className="login-form">
<h1>login</h1>
<div>
<div className="form-group">
<label for="name">
Name :
</label>
<input name="name" type="text" value="" placeholder="Your Name" />
</div>
<div className="form-group">
<label for="password">
Password :
</label>
<input name="password" type="Password" value="" placeholder="Password" />
</div>
<input type="submit">Submit</input>
</div>
</form>
)
}
}
export default Login
I think the issue is here,
//input is an empty tag and you have provided Submit as children here
<input type="submit">Submit</input>
It should be simply this,
<input type="submit" value="Submit" />
ravibagul91's answer is correct. input is self-closing element. You cannot have children in it.
Alternatively, you may use button:
<button type="submit">Submit</button>
To this:
<input type="submit" value="Submit" />

React conditional divs with hooks

I am creating a signup form that will render differently depending on whether the person signing up chooses Post a project or Work on a project from the very first div in the form.
How can I render each div that follows in the form-group conditionally based on what is selected in the first div? I am using hooks and I have found that most examples are for the extends Component approach.
My form:
const signUpForm = () => (
<form onSubmit={clickSubmit}>
<div className="form-group">
<select onChange={handleChange("role")} class="form-control">
<option selected>I want to...</option>
<option>Post a project</option>
<option>Work on a project</option>
</select>
</div>
<div className="form-group">
<input
onChange={handleChange("name")}
type="text"
placeholder="Name"
className="form-control"
value={name}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("email")}
type="email"
placeholder="Email"
className="form-control"
value={email}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("password")}
type="password"
placeholder="Password"
className="form-control"
value={password}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("studying")}
type="text"
placeholder="I'm studying..."
className="form-control"
value={studying}
/>
</div>
<div>
<div>{createInputs()}</div>
<button
className="btn btn-outline-primary btn-sm mb-3"
onClick={addSkill}
type="text"
>
Add more skills
</button>
</div>
<button onClick={clickSubmit} className="btn btn-primary" type="submit">
Sign Up
</button>
</form>
);
State:
const Signup = () => {
const [values, setValues] = useState({
name: "",
email: "",
password: "",
studying: "",
skills: [""],
error: "",
success: "",
role: ""
});
const { name, email, password, studying, skills, success, error, role } = values;
handleChange():
const handleChange = name => event => {
setValues({ ...values, error: false, [name]: event.target.value });
};
You should first divide the signUp in two parts and then call second function based on value of "role" from state.
The idea is to return the divs from second function based on state of first input.
const signUpForm = () => (
<form onSubmit={clickSubmit}>
<div className="form-group">
<select onChange={handleChange("role")} class="form-control">
<option selected>I want to...</option>
<option>Post a project</option>
<option>Work on a project</option>
</select>
</div>
{this.renderInput()}
<button onClick={clickSubmit} className="btn btn-primary" type="submit">
Sign Up
</button>
</form>
);
renderInput() {
if (values.role === "post") {
return (
<div className="form-group">
<input onChange={handleChange("name")} type="text" placeholder="Name" className="form-control" value={name} />
</div>
<div className="form-group">
<input onChange={handleChange("email")} type="email" placeholder="Email" className="form-control" value={email} />
</div>
<div className="form-group">
<input onChange={handleChange("password")} type="password" placeholder="Password" className="form-control" value={password} />
</div>
<div className="form-group">
<input onChange={handleChange("studying")} type="text" placeholder="I'm studying..." className="form-control" value={studying} />
</div>
<div>
<div>{createInputs()}</div>
<button className="btn btn-outline-primary btn-sm mb-3" onClick={addSkill} type="text">
Add more skills
</button>
</div>
);
}
}
You want to test the role state value is truthy/falsey and render the rest of your form on that value.
const SignUpForm = () => (
<form onSubmit={clickSubmit}>
<div className="form-group">
<select
defaultValue='unselected' // set default value here
onChange={handleChange("role")}
className="form-control" // fix className here, class alone isn't correct in react
>
<option value='unselected'>I want to...</option>
<option value='post'>Post a project</option>
<option value='work'>Work on a project</option>
</select>
</div>
{!!role && (
<Fragment>
<div className="form-group">
<input
onChange={handleChange("name")}
type="text"
placeholder="Name"
className="form-control"
value={name}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("email")}
type="email"
placeholder="Email"
className="form-control"
value={email}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("password")}
type="password"
placeholder="Password"
className="form-control"
value={password}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("studying")}
type="text"
placeholder="I'm studying..."
className="form-control"
value={studying}
/>
</div>
<div>
<div>{createInputs()}</div>
<button
className="btn btn-outline-primary btn-sm mb-3"
onClick={addSkill}
type="text"
>
Add more skills
</button>
</div>
</Fragment>
)}
<button onClick={clickSubmit} className="btn btn-primary" type="submit">
Sign Up
</button>
</form>
);

Resources