A state in React holds information that impacts the DOM render and is managed within a component.
Whenever a state is changed the component re-renders thus manipulating the DOM.
You can set a default value for the state and you can also set multiple values e.g an object, in this example the default value for customText state is Watermelon.
const [customText, setCustomText] = useState('Watermelon'); The easiest method to change or update the state is to use setState()
setCustomText('Apple'); This would now change the customText state to Apple and update the DOM content to reflect this.
This Codepen example has a React state with an input that is used to set the state when its value changes.
Explanation:
Whenever the input value is changed it will call on the function handleInputChange and the value is set as the customText state.
<input type="text" value={customText} onChange={handleInputChange} className="..."/> Here the handleInputChange function sets the customText state to the inputs value via the event target method.
let handleInputChange = (event) => {
setCustomText(event.target.value);
} Now just to better showcase the state is this output, If the input is empty “The text is empty will” be shown else it will output the state
{
customText !== "" ? (
<p>
The text is: <span className={"text-bold text-blue-400"}{customText</span>
</p>
) : (
<p>The text is empty</p>
);
}
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Some early September spring shots from a bushwalk, It is still too early for wildflowers.
I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…
If you ever needed a simple solution in Laravel to delete an entire directory and…
How to enforce only one user to register or be registered in a Laravel web…