Professional Documents
Culture Documents
IWP React Lab 2
IWP React Lab 2
function App() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
function handleUsernameChange(e) {
setUsername(e.target.value);
}
function handlePasswordChange(e) {
setPassword(e.target.value);
}
function handleLogin() {
alert("Welcome");
}
return (
<div>
<input type="text" value={username} onChange={handleUsernameChange} />
<input type="password" value={password} onChange={handlePasswordChange} />
<button onClick={handleLogin}>Login</button>
</div>
);
}
importing the useState hook from the React library. The useState hook allows
functional components in React to manage local state.
Prior to the introduction of hooks, state management was primarily done in class components
using the this.state object. However, with the introduction of hooks, functional
components can now manage their own state using the useState hook.
The line const [username, setUsername] = useState(''); in React is using
array destructuring to assign names to the elements returned by the useState hook.
const [username, setUsername]: This line uses array destructuring to extract two
elements from the array returned by the useState hook. The first element (username)
represents the current state value, and the second element (setUsername) is a function that
allows you to update the state.
So, after this line executes:
username will hold the current value of the username state.
setUsername will be a function that you can use to update the value of
username.
setUsername(e.target.value):
This line calls the setUsername function, which is a setter function returned by the
useState hook.
It updates the username state with the value of the input field. e.target.value
retrieves the value of the input field where the change event occurred. So, whenever the
username input field changes, this function updates the username state with the new value.
Output:
function App() {
const [value, setValue] = useState(0);
function incrementValue() {
setValue((prevValue) => prevValue + 1);
}
function decrementValue() {
setValue((prevValue) => prevValue - 1);
}
return (
<div className="App">
<h3>Local State in ReactJS</h3>
<h5>The value managed locally is: {value}</h5>
<div>
<button onClick={incrementValue}>Increment!</button>
<button onClick={decrementValue}>Decrement!</button>
</div>
</header>
</div>
);
}