React form input values in JS - javascript

I am using NextJS with bulma CSS to create a simple application. I have this following form:
const MyPage = () => {
const [firstName, setFirstName] = useState('')
const [secondName, setSecondName] = useState('')
const updateFirstName = event => {
setFirstName(event.target.value)
}
const updateSecondName = event => {
setSecondName(event.target.value)
}
const createUser = async() => {
// Todo: perform some action with firstName and secondName
}
return (
<section className='mt-5'>
<div className='container'>
<div className='field'>
<label className='label'>My Form</label>
<div className='control'>
<input onChange={updateFirstName} className='input' type='type' placeholder='Enter First Name'></input>
</div>
</div>
<div className='field'>
<div className='control'>
<input onChange={updateSecondName} className='input' type='type' placeholder='Enter Second Name'></input>
</div>
</div>
<button onClick={createUser} className='button is-primary'>Create</button>
</div>
</section>
)
}
export default MyPage
I have to call updateFirstName and updateSecondName on every input change.
I want to get these input field's value on createUser() function call only. Please suggest how to do it or any other better approach. I want to eliminate firstName and secondName variables, and directly access entered input in the createUser() function.

If you don't want a controlled input. You can quit managing the state and access the value old way using plain vanilla JS.
Make sure to add name attribute with all the input fields.
function createUser() {
const inputs = document.querySelectorAll(".field input")
let data = {}
inputs.forEach(input => {
data[input.name] = input.value
})
/**
This would yield you
{
'firstname': 'value',
'secondName': 'value'
}
**/
}

Please change your input fields as shown below:
<input onChange={(e)=>createUser(e,'firstName')} className='input' type='type' placeholder='Enter First Name'></input>
<input onChange={(e)=>createUser(e,'lastName')} className='input' type='type' placeholder='Enter First Name'></input>
Then in your update your createUser function as shown below:
const createUser = (event, element) => {
if(element==='firstName') {
setFirstName(event.target.value)
}
if(element==='lastName') {
setLastName(event.target.value)
}
}

You can try alternatively with this useRef() hook,
const MyPage = () => {
const firstName = useRef();
const secondaName = useRef();
const createUser = async() => {
// Todo: perform some action with firstName and secondName
console.log(firstName.current.value, secondName.current.value) // It will prints the value that is typed by the user in both the textfields
}
return (
<section className='mt-5'>
<div className='container'>
<div className='field'>
<label className='label'>My Form</label>
<div className='control'>
<input ref={firstName} className='input' type='type' placeholder='Enter First Name'></input>
</div>
</div>
<div className='field'>
<div className='control'>
<input ref={secondName} className='input' type='type' placeholder='Enter Second Name'></input>
</div>
</div>
<button onClick={createUser} className='button is-primary'>Create</button>
</div>
</section>
)
}
export default MyPage

You can write a handler function
Firstly, you should add all variables to same state.
const [userInfo, setUserInfo] = useState({
firstName: "",
secondName: ""
});
and you should give a name to inputs like this.
<input
className="input"
onChange={onChangeHandler}
name="firstName" //name attribute must same your state variable
placeholder="Enter First Name"
/>
<input
className="input"
onChange={onChangeHandler}
name="secondName" //name attribute must same your state variable
placeholder="Enter Second Name"
/>
and your handler function should like this
const onChangeHandler = (e) =>
setUserInfo({ ...userInfo, [e.target.name]: e.target.value });
and this function take your input value and set your state who same name.
Full code
export default function App() {
const [userInfo, setUserInfo] = useState({
firstName: "",
secondName: ""
});
const onChangeHandler = (e) =>
setUserInfo({ ...userInfo, [e.target.name]: e.target.value });
const sendData = () => {
console.log(userInfo);
};
return (
<div className="App">
<section className="mt-5">
<div className="container">
<div className="field">
<label className="label">My Form</label>
<div className="control">
<input
className="input"
onChange={onChangeHandler}
name="firstName"
placeholder="Enter First Name"
/>
</div>
</div>
<div className="field">
<div className="control">
<input
className="input"
onChange={onChangeHandler}
name="secondName"
placeholder="Enter Second Name"
/>
</div>
</div>
<button onClick={sendData} className="button is-primary">
Create
</button>
</div>
</section>
</div>
);
}
https://codesandbox.io/s/gallant-pasteur-uglbri?file=/src/App.js:58-1264

Related

TypeError: Cannot read properties of null (reading 'name') for [event.target.name]: event.targe.value

I'm creating a simple controlled component form in react. When I console log event.target.name on onChange event it logs fine but when I setState using computed property name of the object in javascript it gives me an error TypeError: Cannot read properties of null (reading 'name')
This never happened before and I've created many working projects where I created the form similar way. Could you please explain why all of sudden these issues occurring to me?
import "./Contact.css";
import React from "react";
const Contact = () => {
const [contactFormValues, setContactFormValues] = React.useState({
fName: "",
lName: "",
email: "",
phone: "",
message: "",
});
const handleChange = (event) => {
setContactFormValues((prevValues) => ({
...prevValues,
[event.target.name]: event.target.value, // Here, this line gives me error
}));
};
const handleSubmit = async (event) => {
event.preventDefault();
console.log(contactFormValues);
}
return (
<>
<div className="contact-form">
<div className="contact-container">
<div className="left-section">
<div className="title">
<h1>Write Us</h1>
</div>
<div className="row">
<div className="contact-sub-row">
<label className="contact-label">First Name</label>
<input
className="contact-input"
type="text"
name="fName"
onChange={handleChange}
value={contactFormValues.fName}
required
/>
</div>
<div className="contact-sub-row">
<label className="contact-label">Last Name</label>
<input
className="contact-input"
type="text"
name="lName"
onChange={handleChange}
// value={contactFormValues.lName}
required
/>
</div>
</div>
<div className="contact-sub-row">
<label className="contact-label">Email</label>
<input
className="contact-input is-success"
type="email"
name="email"
onChange={handleChange}
// value={contactFormValues.email}
required
/>
</div>
<div className="contact-sub-row">
<label className="contact-label">Phone</label>
<input
className="contact-input"
type="tel"
placeholder="1-123-456-7890"
maxlength="20"
name="phone"
onChange={handleChange}
value={contactFormValues.phone}
required
/>
</div>
</div>
<div className="right-section">
<div className="your-message">
<label className="contact-label">Message</label>
<textarea
className="contact-textarea"
name="message"
placeholder="Write text here..."
onChange={handleChange}
value={contactFormValues.message}
required
></textarea>
</div>
<div className="contact-btns">
<button className="submit-btn" onClick={handleSubmit}>SEND MESSAGE</button>
</div>
</div>
</div>
</div>
</>
);
};
export default Contact;
Wrap the inputs in a form tag element.
and try this:
const handleChange = (event) => {
const { name, value } = event.target;
setContactFormValues({ ...contactFormValues, [name]: value });
}
I've done this in our very last project.

How to pass data between components in react?

I have been trying to display the form data submitted but the map is throwing an error.
I have two components
NameForm.js
Here is the form input, handlechange and handlesubmit methods are done
function Nameform() {
const [form, setForm] = useState({firstname: "", lastname: ""});
const handleChange = (e) => {
setForm({
...form,
[e.target.id]: (e.target.value),
});
};
const handleSubmit = (e) => {
e.preventDefault();
console.log("hello from handle submit", form );
}
return (
<section>
<div className='card pa-30'>
<form onSubmit={ handleSubmit }>
<div className='layout-column mb-15'>
<label htmlFor='name' className='mb-3'>First Name</label>
<input
type='text'
id='firstname'
placeholder='Enter Your First Name'
data-testid='nameInput'
value={form.firstname}
onChange={handleChange}
/>
</div>
<div className='layout-column mb-15'>
<label htmlFor='name' className='mb-3'>First Name</label>
<input
type='text'
id='firstname'
placeholder='Enter Your First Name'
data-testid='nameInput'
value={form.firstname}
onChange={handleChange}
/>
</div>
<div className='layout-row justify-content-end'>
<button
type='submit'
className='mx-0'
data-testid='addButton'
>
Add Name
</button>
</div>
</form>
</div>
</section>
)
}
export default Nameform
NameList.js
I want to pass the data in handleSubmit in NameForm.js to NameList.js. But the data is not displayed.
function NameList({form}) {
return (
<section>
{form.map(displayName => {
return (
<ul
className='styled w-100 pl-0'
>
<li
className='flex slide-up-fade-in justify-content-between'
>
<div className='layout-column w-40'>
<h3 className='my-3'>{displayName.firstname}</h3>
<p className='my-0'{displayName.lastname}></p>
</div>
</li>
</ul>
)
})}
</section>
)
}
export default NameList;
App.js
In App.js, I want to display both the form and the data.
import { Nameform, Namelist } from './components'
function App() {
return (
<div>
<div className='layout-row justify-content-center mt-100'>
<div className='w-30 mr-75'>
<Nameform />
</div>
<div className='layout-column w-30'>
<NameList />
</div>
</div>
</div>
)
}
export default App;
Thank you for your help!
Pass the data you want to share between parent and children via props (which stands for properties).
In the parent class, when rendering <NameForm> and <ListForm> add the data like that:
//if you want to share count and name for example:
<NameForm
count={this.state.count}
name={this.state.name}
/>
You can add as many props as you want. Furthermore, you can pass a function and its argument using arrow functions:
<NameForm
aFunction={() => this.myFunction( /* anArgument */ )}
/>
To access props in a child class dynamically wherever you need them:
{this.props.count}
{this.props.name}
{this.props.aFucntion}
You can get rid of this.props using a technique called object destructing:
render(
const {count, name, aFunction} = this.props;
//now you can use {count} and {name} and {aFunction} without this.props
);
There are some bugs in your code, first form is an object not an array, so you can't map it, you need to use form.firstname and form.lastname, Also you set both input ids equal firstname you need to modify it, Also you need to move the form state and handleChange function to the App component.
This is a working code of your example.
https://codesandbox.io/s/upbeat-forest-328bon
You can save the state in the parent component and pass it as props to the child components like so.
Here we make use of an outer state called submittedForm to display only the submitted values. The inner form state is being used for handling the values before submitting.
// App.js
function App() {
const [submittedForm, setSubmittedForm] = useState({
firstname: "",
lastname: "",
});
return (
<div>
<div className="layout-row justify-content-center mt-100">
<div className="w-30 mr-75">
<NameForm setSubmittedForm={setSubmittedForm} />
</div>
<div className="layout-column w-30">
<NameList form={submittedForm} />
</div>
</div>
</div>
);
}
export default App;
// NameForm.js
function NameForm({ setSubmittedForm }) {
const [form, setForm] = useState({
firstname: "",
lastname: "",
});
const handleChange = (e) => {
// setActive(true);
setForm({
...form,
[e.target.id]: e.target.value,
});
};
const handleSubmit = (e) => {
e.preventDefault();
setSubmittedForm(form);
};
return (
<section>
<div className="card pa-30">
<form onSubmit={handleSubmit}>
<div className="layout-column mb-15">
<label htmlFor="name" className="mb-3">
First Name
</label>
<input
type="text"
id="firstname"
placeholder="Enter Your First Name"
data-testid="nameInput"
value={form.firstname}
onChange={handleChange}
/>
</div>
<div className="layout-column mb-15">
<label htmlFor="name" className="mb-3">
Last Name
</label>
<input
type="text"
id="lastname"
placeholder="Enter Your Last Name"
data-testid="nameInput"
value={form.lastname}
onChange={handleChange}
/>
</div>
<div className="layout-row justify-content-end">
<button type="submit" className="mx-0" data-testid="addButton">
Add Name
</button>
</div>
</form>
</div>
</section>
);
}
export default NameForm;
// NameList.js
function NameList({ form }) {
return (
<section>
<ul className="styled w-100 pl-0">
<li className="flex slide-up-fade-in justify-content-between">
<div className="layout-column w-40">
<h3 className="my-3">{form.firstname}</h3>
<p className="my-0">{form.lastname}</p>
</div>
</li>
</ul>
</section>
);
}
export default NameList;

How can I persist updated form data after submit?

So I have some formdata in my react app that I want to persist after I make a put request to the mongodb. Problem is that the change is not visible on page refresh. It is only after I log out and log in again that I can see the updated value in the form.
For example let's say that I want to change my first name from John to Eric. The change will update but not in the form. In the form the value will still be John until I log out and in again.
It feels almost like it has to do with the jwt token but I don't know. Any ideas what the problem can be?
export const Edit = () => {
const navigate = useNavigate();
const user = Cookies.get("access_token");
const [id, setId] = useState(null)
const [firstName, setFirstName] = useState("")
const [lastName, setLastName] = useState("")
const [city, setCity] = useState("")
const [email, setEmail] = useState("")
const checkUser = async () => {
try {
const res = await axios
.get(`${process.env.REACT_APP_API_URL}user/protected`, {
withCredentials: true,
headers: {
Authorization: `Bearer ${user}`,
},
})
console.log(res.data.user);
setId(res.data.user.id)
setFirstName(res.data.user.firstName)
setLastName(res.data.user.lastName)
setCity(res.data.user.city)
setEmail(res.data.user.email)
} catch (error) {
console.warn(error)
}
}
useEffect(() => {
if (!user) {
navigate('/')
} else {
checkUser();
}
}, []);
const updateUser = async () => {
try {
const userData = {
firstName: firstName,
lastName: lastName,
city: city,
email: email
}
const API_URL = `${process.env.REACT_APP_API_URL}user/`;
const userId = id;
const res = await axios.put(API_URL + "/" + userId + "/edit", userData)
setFirstName(res.data.firstName)
setLastName(res.data.lastName)
setCity(res.data.city)
setEmail(res.data.email)
// works and is updated in the database
} catch (error) {
console.warn(error)
}
}
return (
<>
<section className="m-5">
<h1 className="mb-5 text-center">Settings</h1>
<form className="row g-3">
<div className="col-md-6">
<label htmlFor="firstName" className="form-label">
First name
</label>
<p>{formErrors.firstName}</p>
<input
type="text"
className="form-control"
id="firstName"
name="firstName"
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
/>
</div>
<div className="col-md-6">
<label htmlFor="lastName" className="form-label">
Last name
</label>
<p>{formErrors.lastName}</p>
<input
type="text"
className="form-control"
id="lastName"
name="lastName"
value={lastName}
onChange={(e) => setLastName(e.target.value)}
/>
</div>
<div className="col-md-6">
<label htmlFor="city" className="form-label">
City
</label>
<p>{formErrors.city}</p>
<input
type="text"
className="form-control"
id="city"
name="city"
value={city}
onChange={(e) => setCity(e.target.value)}
/>
</div>
<div className="col-md-6">
<label htmlFor="email" className="form-label">
Email
</label>
<p>{formErrors.email}</p>
<input
type="email"
className="form-control"
id="email"
name="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="col-12 pt-4 text-center">
<button
type="submit"
className="btn btn-primary btn-lg"
onClick={updateUser}
>
Update
</button>
</div>
<div className="col-12 pt-1 text-center">
<button
type="submit"
className="btn btn btn-lg"
>
<a href="edit/password" className="text-decoration-none">
Change Password
</a>
</button>
</div>
</form>
</section>
</>
);
};
Add user as a dependency to the useEffect's dependency array:
useEffect(() => {
if (!user) {
navigate('/')
} else {
checkUser();
}
}, [user]);

REACT: SELECT from MYSQL

i a new user and a new in React world. I need help to solve this situation about a Select with values from mysql DB.
I receive the values, but the select goes in infinite loop.
The error is surely in this file cause server.js works without problem!!
Really thanks for the help, and sorry if it could be a stupid question. I m studying react from one week and i have not found answers on internet
function FormAddMenu({ registerMenu }) {
const [nomeMenuReg, setNomeMenuReg] = useState("");
const [descrizioneMenuReg, setDescrizioneMenuReg] = useState("");
const [prezzoMenuReg, setPrezzoMenuReg] = useState("");
const [disponibilitaMenuReg, setDisponibilitaMenuReg] = useState("");
const [portataMenuReg, setPortataMenuReg] = useState("");
const [addMenu, setAddMenu] = useState({
portataMenuReg: "",
nomeMenuReg: "",
descrizioneMenuReg: "",
prezzoMenuReg: "",
disponibilitaMenuReg: "",
});
const [portate, setPortate] = useState({ value: "", label: "" });
const selectOptions = async () => {
Axios.post("http://localhost:3001/selectPortata").then((response) => {
// console.log("risposta:",response.data)
setPortate(
response.data.map((risp) => ({
...setPortate,
value: risp.value,
label: risp.label,
})),
);
});
};
selectOptions();
console.log("portate:", portate);
const submitHandler = (e) => {
e.preventDefault();
registerMenu(addMenu);
document.getElementById("addmenu").reset();
};
const handleCheckbox = (e) => {
console.log(e.target.checked);
if (e.target.checked === true) {
setAddMenu({ ...addMenu, disponibilitaMenuReg: 1 });
} else {
setAddMenu({ ...addMenu, disponibilitaMenuReg: e.target.value });
}
};
return (
<div className="container width85">
<h1>CREA IL MENU'</h1>
<form id="addmenu">
<div className="mb-3">
<label htmlFor="portataMenuReg" className="form-label">
PORTATA
</label>
<Select
options={portate}
onChange={(e) => setAddMenu({ ...addMenu, portataMenuReg: e.target.value })}
className="mb-3"
/>
</div>
<div className="mb-3">
<label htmlFor="nomeMenuReg" className="form-label">
NOME
</label>
<input
type="text"
onChange={(e) => setAddMenu({ ...addMenu, nomeMenuReg: e.target.value })}
className="form-control"
id="nomeMenuReg"
rows="3"
/>
</div>
<div className="mb-3">
<label htmlFor="descrizioneMenuReg" className="form-label">
DESCRIZIONE
</label>
<textarea
className="form-control"
onChange={(e) =>
setAddMenu({ ...addMenu, descrizioneMenuReg: e.target.value })
}
id="descrizioneMenuReg"
rows="3"
></textarea>
</div>
<div className="mb-3">
<label htmlFor="prezzoMenuReg" className="form-label">
PREZZO
</label>
<input
type="text"
className="form-control"
onChange={(e) => setAddMenu({ ...addMenu, prezzoMenuReg: e.target.value })}
id="prezzoMenuReg"
rows="3"
/>
</div>
<div className="mb-3">
<label htmlFor="disponibilitaMenuReg" className="form-label">
DISPONIBILITA'
</label>
<input
type="checkbox"
value="0"
className="htmlForm-control"
onChange={handleCheckbox}
id="disponibilitaMenuReg"
rows="3"
/>
</div>
<div className="mb-3">
<button type="submit" onClick={submitHandler} className="btn btn btn-danger">
AGGIUNGI AL MENU
</button>
</div>
</form>
</div>
);
}
export default FormAddMenu;
Wrap the selectOptions(); call in an useEffect (since loading data and mutating state based on it is a side effect).
The empty dependency array (documented above) means the effect is only executed once on mount.
React.useEffect(() => {
selectOptions();
}, []);

how to render input values on button click react

I have two fields and a button. I want to render input values on the click of a button. Can you guys please tell me how to do it?
function Home() {
const [name, setName] = useState('')
const [age, setAge] = useState(0)
const submitForm = () => {
console.log(name, age)
}
return (
<div>
<div>
<label htmlFor="name">Name:</label>
<input type="text" value={name} onChange={e => setName(e.target.value)} />
</div>
<div>
<label htmlFor="age">age:</label>
<input type="number" value={age} onChange={e => setAge(e.target.value)} />
</div>
<button onClick={submitForm}>Submit</button>
<h1>render "name" gere</h1>
<h2>render "age" gere</h>
</div>
)
}
export default Home
You can add a state to track the display state, as
const [visible, setVisible] = useState(false)
Alter it in form submit as:
const submitForm = () => {
setVisible(true)
}
And render it as:
{visible && <><h1>render {name} gere</h1>
<h2>render {age} gere</h2> </>}
I fix it like this.
function Home() {
const [name, setName] = useState('')
const [age, setAge] = useState(0)
const [data, setData] = useState({})
const submitForm = () => {
setData({name, age})
}
return (
<div>
<div>
<label htmlFor="name">Name:</label>
<input type="text" value={name} onChange={e => setName(e.target.value)} />
</div>
<div>
<label htmlFor="age">age:</label>
<input type="number" value={age} onChange={e => setAge(e.target.value)} />
</div>
<button onClick={submitForm}>Submit</button>
<h1>{data.name}</h1>
<h2>{data.age}</h2>
</div>
)
}
export default Home
Try this and see if it helps.
function Home() {
const {register, handleSubmit} = useForm()
const onSubmit = (data) => {
console.log(data)
}
return (
<form onSubmit = {handleSubmit(onSubmit)}>
<div>
<div>
<label htmlFor="name">Name:</label>
<input type="text" value={name} onChange={e => setName(e.target.value)} />
</div>
<div>
<label htmlFor="age">age:</label>
<input type="number" value={age} onChange={e => setAge(e.target.value)} />
</div>
<button onSubmit={submitForm}>Submit</button>
<h1>render "name" gere</h1>
<h2>render "age" gere</h>
</div>
<form/>
);
}

Categories

Resources