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.