Search code examples
typescriptpreactconditional-rendering

Preact/typeScript conditional rendering "expression expected"


Hello all i want to do is a simple conditional rendering which i have done in react before but i cant seem to do it in preact.

 export const InfoSection = (props: Props) => 
    {
        return (
            <div>
                <table>
                    <tr>
                        <th>#</th>
                        <th>User</th>
                        <th>Info</th>
                        <th>date</th>
                    </tr>
                    {
                        props.infoEntries.map( (l, i) => 
                        {
                            return (
                                <tr>
                                    <td>{i+1}</td>
                                    <td{l.UserId}</td>
                                    <td>{l.Info}</td>
                                    <td>{l.Date}</td>
                                </tr>
                            )
                        })
                    }
                    {
                        if(this.props.showEntryDetails){
                            return(
                        <tr>
                          <td>"Hello"</td>
                        </tr>
                    )
                        }
                    }
                </table>
            </div>
        )
    }

as you see at the bottom i just try to use an if on showEntryDetails but here i get an error saying "Expression Expected" i think this is a typescript error but i don´t know why it wont let me have an if there. Anyone who can explain to me why and if there is a way to do what i want to?


Solution

  • In JavaScript (thus in TypeScript as well), there are expressions and statements. You can use expressions as statements, but not vice versa.

    if is a statement, but JSX's curly brackets expect only expressions. The proper way to do conditional rendering is to use &&:

    {this.props.showEntryDetails && (
        <tr>
            <td>"Hello"</td>
        </tr>
    )}