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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago