From c8d6ede1e4c3aebcf60618836155dce8c43655fd Mon Sep 17 00:00:00 2001 From: Zehan Khan Date: Tue, 19 Mar 2024 02:00:34 +0530 Subject: [PATCH 01/23] feat: update react.md --- source/_posts/react.md | 187 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 186 insertions(+), 1 deletion(-) diff --git a/source/_posts/react.md b/source/_posts/react.md index 7743c74..db3c2d0 100644 --- a/source/_posts/react.md +++ b/source/_posts/react.md @@ -382,4 +382,189 @@ export default function Weather(props) { } } ``` -Note: Make sure to import Axios first to your project. \ No newline at end of file +Note: Make sure to import Axios first to your project. + + +HOOKS +------------ + +### useState Hook + +```javascript +import React, { useState } from "react"; + +function Counter() { + const [count, setCount] = useState(0); + + return ( +
+

Count: {count}

+ +
+ ); +} + +export default Counter; +``` +Note: The useState Hook is a built-in React Hook that allows functional components to manage local state. It provides a way to declare state variables and update them within a functional component. +Example code illustrating how to use it + + +### Multiple State Variable Declaration + +```javascript +import React, { useState } from "react"; + +function Counter() { + const [count, setCount] = useState(0); + const [name, setName] = useState(""); + const [isCompleted, setIsCompleted] = useState(false); + + const handleIncrement = () => { + setCount(count + 1); + }; + + const handleNameChange = (event) => { + setName(event.target.value); + }; + + const toggleCompletion = () => { + setIsCompleted(!isCompleted); + }; + + return ( +
+

Count: {count}

+ + + + + +
+ ); +} + +export default Counter; +``` +Note: You can declare multiple state variables using the useState Hook by calling it multiple times in a functional component. Each call to useState manages a separate piece of state. + +### Input State Management + +```javascript +import { useState } from "react"; + +function FormExample() { + const [formData, setFormData] = useState({name: "",email: "",message: ""}); + + const handleChange = (event) => { + const { name, value } = event.target; + setFormData((prevFormData) => ({ ...prevFormData, [name]: value })); + }; + + const handleSubmit = (event) => { + event.preventDefault(); + alert(`Name: ${formData.name}, Email: ${formData.email}, Message: ${formData.message}` + ); +}; + + return ( +
+ + + + + + + +