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…

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