Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JS nested conditions, unexpected error on .map()

I'm trying to do nested conditionals to be rendered and one case would make me use .map()

renderClasses () {
        if (!this.state.classes.length) {
            console.log(this.state.userType)
            if (this.state.userType) return(<div>Add Class</div>)
            else return (<div>Join Class</div>)
        } else {
            return (<div>{
                this.state.classes.map((class) => {
                                             ^ unexpected token here 
                    <div>one class</div>
                })
            }</div>)
        }
    }

    render() {
        if (!this.state.isLogged) {
            return <Redirect to='/' />
        }
        return (
            <div>
                {
                    this.renderClasses()
                }
            </div>
        );
    }

Am i missing something? i tried wrapping everything into one <div> or maybe I understood it wrong? Thank you in advance

like image 452
adv Avatar asked Apr 07 '26 03:04

adv


2 Answers

you do not return anything:

this.state.classes.map((item) => {
   <div>one class</div>
})

try to paste return statement

this.state.classes.map((item) => {
   return <div>one class</div>
})

But the error is cause by class being a reserved keyword, try to name it like item.

like image 115
Tomasz Mularczyk Avatar answered Apr 08 '26 18:04

Tomasz Mularczyk


If you use {} in map function you need to use return as well. If its just a single statement, just ignore {}. You can use this -

this.state.classes.map(class => <div>one class</div>)
like image 37
Rishikesh Dhokare Avatar answered Apr 08 '26 16:04

Rishikesh Dhokare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!