Preact/typeScript conditional rendering "expression expected"
Asked Answered
D

1

6

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?

Demonic answered 4/12, 2018 at 9:29 Comment(0)
R
7

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>
)}
Rovner answered 4/12, 2018 at 10:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.