Categories: Development

Learning React JS Part 3 (States)

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.

React state example

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>
  );
}

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago