Categories: Development

Learning React JS Part 4

Writing out conditionals in React that change the state of your Application. The conditionals are written very similarly to Javascript but you have to consider the rules of JSX.

The example below are written in formatting and style for the .jsx format

Else if conditional

Here is a method I have found to be the most cleanest and readable to do multiple else if statements in React

{
    (() => {
        if (book.rating >= 8) {
            return (<p>Rated amazing</p>);
        } else if (book.rating >= 6) {
            return (<p>Rated great</p>);
        } else if (book.rating >= 4) {
            return (<p>Rated ok</p>);
        } else {
            return (<p>Rated poorly</p>)
        }
    })()
}

These are basic conditionals but is a good example of laying out the whole path.

You can of course do a ternary or inline for a simple conditional

{(book.on_sale)? "<p>On sale</p>" : "<p>Normal price</p>"}

Assign variables from a conditional

{
    if (book.quantity > 0) {
        button = <BuyButton onClick={this.handleBuyClick}/>;
    } else {
        button = <NotifyButton onClick={this.handleNotifyClick}/>;
    }
}

 

Using setData multiple times

Using multiple setData() calls from a hook or function will only effectively write the last occurrence

setData('product_name', productName);
setData('category_id', CategoryId);

In the above case only category_id will be set.

To use setData() multiple times it must be done with this method:

setData(data => ({ ...data, product_name: ProductName}));
setData(data => ({ ...data, category_id: CategoryId}));

This way accesses the data object key & value and overwrites it.

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