review
sidebar_label: 'React Events' sidebar_position: 25 hide_title: true title: 'React Events' draft: true
for loop arr. 1-5
const arr: number[] = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
for of loop 1-5
const arr: number[] = [1, 2, 3, 4, 5];
for (const element of arr) {
console.log(element);
}
foreach array 1-5
const arr: number[] = [1, 2, 3, 4, 5];
arr.forEach((element) => {
console.log(element);
});
while loop array 1-5
const arr: number[] = [1, 2, 3, 4, 5];
let i = 0;
while (i < arr.length) {
console.log(arr[i]);
i++;
}
Input box input
interface MyComponentProps {
onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
}
const MyComponent = ({ onChange }: MyComponentProps) => {
const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
console.log(event.target.value);
}
return <input onChange={onChange} />;
};
onClick
interface MyComponentProps {
onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
}
const MyComponent = ({ onClick }: MyComponentProps) => {
const onClick = (event: React.MouseEvent<HTMLButtonElement>) => {
console.log(event.target.value);
}
return <button onClick={onClick}>Click Me</button>;
};
Basic Counter
interface MyComponentProps {
initialCount: number;
}
const MyComponent = ({ initialCount }: MyComponentProps) => {
const [count, setCount] = React.useState<number>(initialCount);
React.useEffect(() => {
console.log("Count changed:", count);
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
Understanding how to use useRef:
interface MyComponentProps {
initialText: string;
}
const MyComponent = ({ initialText }: MyComponentProps) => {
const inputRef = React.useRef<HTMLInputElement>(null);
React.useEffect(() => {
if (inputRef.current) {
inputRef.current.value = initialText;
}
}, [initialText]);
return <input type="text" ref={inputRef} />;
};
Typing custom hooks:
interface UseCounterResult {
count: number;
increment: () => void;
}
const useCounter = (initialCount: number): UseCounterResult => {
const [count, setCount] = React.useState<number>(initialCount);
const increment = () => {
setCount(count + 1);
};
return { count, increment };
};
const MyComponent = () => {
const { count, increment } = useCounter(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
};
useState: Avoiding stale state:
When updating state based on previous state, it's important to use the function form of setState to avoid stale state issues.
interface MyComponentProps {
initialCount: number;
}
const MyComponent = ({ initialCount }: MyComponentProps) => {
const [count, setCount] = React.useState(initialCount);
const increment = () => {
setCount((prevCount) => prevCount + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
};
useToggle custom hook
import { Dispatch, SetStateAction, useCallback, useState } from 'react'
function useToggle(
defaultValue?: boolean,
): [boolean, () => void, Dispatch<SetStateAction<boolean>>] {
const [value, setValue] = useState(!!defaultValue)
const toggle = useCallback(() => setValue(x => !x), [])
return [value, toggle, setValue]
}
export default useToggle
Usage
import { useToggle } from '..'
export default function Component() {
const [value, toggle, setValue] = useToggle()
// Just an example to use "setValue"
const customToggle = () => setValue((x: boolean) => !x)
return (
<>
<p>
Value is <code>{value.toString()}</code>
</p>
<button onClick={() => setValue(true)}>set true</button>
<button onClick={() => setValue(false)}>set false</button>
<button onClick={toggle}>toggle</button>
<button onClick={customToggle}>custom toggle</button>
</>
)
}
useContext
Create context
import { createContext } from 'react';
interface MyContextProps {
message: string;
setMessage: (message: string) => void;
}
const MyContext = createContext<MyContextProps>({
message: '',
setMessage: () => {},
});
export default MyContext;
import React from 'react';
import MyContext from './MyContext';
const MyComponent = () => {
const { message, setMessage } = React.useContext(MyContext);
return (
<div>
<p>Message: {message}</p>
<button onClick={() => setMessage("Hello World")}>Set Message</button>
</div>
);
};
export default MyComponent;
Provider
import React from 'react';
import MyContext from './MyContext';
const MyProvider = () => {
const [message, setMessage] = React.useState<string>('');
return (
<MyContext.Provider value={{ message, setMessage }}>
<MyComponent />
</MyContext.Provider>
);
};
useReducer
import React from 'react';
interface MyComponentProps {
initialCount: number;
}
interface MyComponentState {
count: number;
}
type MyComponentAction = { type: 'increment' } | { type: 'decrement' };
const initialState: MyComponentState = {
count: 0,
};
const reducer = (
state: MyComponentState,
action: MyComponentAction,
): MyComponentState => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
};
const MyComponent = ({ initialCount }: MyComponentProps) => {
const [state, dispatch] = React.useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
};
export default MyComponent;
Checkbox component
import React, { useState } from "react";
import "./Checkbox.css";
interface CheckboxProps {
label: string;
defaultChecked?: boolean;
onChange?: (checked: boolean) => void;
}
const Checkbox = ({
label,
defaultChecked = false,
onChange = () => {},
}: CheckboxProps) => {
const [checked, setChecked] = useState(defaultChecked);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const isChecked = e.target.checked;
setChecked(isChecked);
onChange(isChecked);
};
return (
<div className="checkbox">
<input
type="checkbox"
checked={checked}
onChange={handleChange}
className="checkboxInput"
/>
<label className="checkboxLabel">{label}</label>
</div>
);
};
export default Checkbox;
useToggle
import { Dispatch, SetStateAction, useCallback, useState } from 'react'
function useToggle(
defaultValue?: boolean,
): [boolean, () => void, Dispatch<SetStateAction<boolean>>] {
const [value, setValue] = useState(!!defaultValue)
const toggle = useCallback(() => setValue(x => !x), [])
return [value, toggle, setValue]
}
export default useToggle
import { useToggle } from 'usehooks-ts'
export default function Component() {
const [value, toggle, setValue] = useToggle()
// Just an example to use "setValue"
const customToggle = () => setValue((x: boolean) => !x)
return (
<>
<p>
Value is <code>{value.toString()}</code>
</p>
<button onClick={() => setValue(true)}>set true</button>
<button onClick={() => setValue(false)}>set false</button>
<button onClick={toggle}>toggle</button>
<button onClick={customToggle}>custom toggle</button>
</>
)
}