- Get link
- X
- Other Apps
Featured Post
- Get link
- X
- Other Apps
Are u using usesState Hook Like This:
import React, { useState } from 'react';
function ContactForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [subject, setSubject] = useState('');
const [message, setMessage] = useState('');
function handleNameChange(event) {
setName(event.target.value);
}
function handleEmailChange(event) {
setEmail(event.target.value);
}
function handleSubjectChange(event) {
setSubject(event.target.value);
}
function handleMessageChange(event) {
setMessage(event.target.value);
}
return (
<form>
<input
type="text"
placeholder="Name"
value={name}
onChange={handleNameChange}
/>
<input
type="email"
placeholder="Email"
value={email}
onChange={handleEmailChange}
/>
<input
type="text"
placeholder="Subject"
value={subject}
onChange={handleSubjectChange}
/>
<textarea
placeholder="Message"
value={message}
onChange={handleMessageChange}
/>
</form>
);
}
if u are using usestate like this, then this is a wrong way to do this in react:
import React, { useReducer } from 'react';
const initialState = {
name: '',
email: '',
subject: '',
message: ''
};
function reducer(state, action) {
switch (action.type) {
case 'name':
return { ...state, name: action.value };
case 'email':
return { ...state, email: action.value };
case 'subject':
return { ...state, subject: action.value };
case 'message':
return { ...state, message: action.value };
default:
return state;
}
}
function ContactForm() {
const [state, dispatch] = useReducer(reducer, initialState);
function handleChange(event) {
dispatch({
type: event.target.name,
value: event.target.value
});
}
return (
<form>
<input
type="text"
name="name"
placeholder="Name"
value={state.name}
onChange={handleChange}
/>
<input
type="email"
name="email"
placeholder="Email"
value={state.email}
onChange={handleChange}
/>
<input
type="text"
name="subject"
placeholder="Subject"
value={state.subject}
onChange={handleChange}
/>
<textarea
name="message"
placeholder="Message"
value={state.message}
onChange={handleChange}
/>
</form>
);
}
In this example, the component is using a single `useReducer` hook instead of multiple `useState` hooks. The `reducer` function takes care of updating the state based on the action type and value. The `handleChange` function is used to dispatch an action with the input’s name and value when the input’s value changes. And the `name`, `email`, `subject`, and `message` properties of the state are used to set the values of the corresponding form inputs.
This approach helps in making the component more organized and maintainable. The state is centralized and the logic for updating the state is separated from the component’s render logic.
- Get link
- X
- Other Apps
Comments
Post a Comment