si2030
si2030

Reputation: 4045

Problems with React.js conditional statement within another conditional statement

The intention is to conditionally display elements if "sortBy" is equal to a particular value..

I can do a single conditional statement but when I add another inside the first one it errors with

Exception: Call to Node module failed with error: TypeError: "LastName" is not a function

Here is my code:

export const TableHeaders = (props) => {
    const { handleSubmit } = props

    const { sortBy, sortDirection} = props

    return (
        <div>
        <div className="row">
            <div className="col-md-1" style={headingCellStyle}>Client #</div>
            <div className="col-md-6" style={headingCellStyle}>
            Name / Address
            {sortBy === 'LastName' (
                <span>
                {sortDirection === 'Descending' ? (
                    <span className='glyphicon glyphicon-sort-by-attributes'></span>
                    ) : (
                    <span className='glyphicon glyphicon-sort-by-attributes-alt'></span>
                    )
                }
                </span>
            )}

            {console.log(`Sort Direction ${sortDirection}`)}
            </div>
            <div className="col-md-2" style={headingCellStyle}>Phone</div>
            <div className="col-md-1" style={headingCellStyle}>Jobs</div>
            <div className="col-md-2" style={headingCellStyle}>Actions</div>
        </div>
        </div>
    )
    }
    TableHeaders.propTypes = {
    onSubmit: PropTypes.func.isRequired,
    }

    const TableHeadersForm = reduxForm({
    form: 'SearchClients',
    })(TableHeaders)

    export default TableHeadersForm

How do I structure a double conditional statement here?

I found that just the"sortDirection" conditional statement only works but adding the "sortBy" condtional statement around it fails.

I'm first intending to check if "sortby" is equal to say "LastName" and if so then check "sortDirection" is either "Ascending" or "Descending" and display a glyphon accordingly..

Upvotes: 0

Views: 245

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104529

You missed a ? as well as the false case of first condition, You need to write it like this:

{sortBy === 'LastName' ?
    <span>
    {
        sortDirection === 'Descending' ? 
            <span className='glyphicon glyphicon-sort-by-attributes'></span>
        : 
            <span className='glyphicon glyphicon-sort-by-attributes-alt'></span>
    }
    </span>
:
    null //or some element
}

If you don't want to render anything in false case you can write it like this also:

{sortBy === 'LastName' && <span>
    {
        sortDirection === 'Descending' ? 
            <span className='glyphicon glyphicon-sort-by-attributes'></span>
        : 
            <span className='glyphicon glyphicon-sort-by-attributes-alt'></span>
    }
    </span>
}

Upvotes: 1

Related Questions