0

I am new to react and trying to display nested json object. I want to iterate "hookah_tobacco" nested object and display tobacco types.

Json part:

{
"id": 1,
"hookah_name": "Smoke city",
"city": 131,
"street": "Osinnya, 33",
"website": "",
"phone": "0672222222",
"description": "Cool bar.",
"credit_card": true,
"hookah_type": [],
"hookah_tobacco": [
    {
        "hookah_tobacco": "Al-Fakher"
    },
    {
        "hookah_tobacco": "Serbetli"
    }
],
"summer_terrace": false,
"hookah_images": [
    {
        "id": 1,
        "hookah_image": "http://127.0.0.1:8000/hookahImages/O4P02PtmT22nv8LwB85KDw-752x440.jpg"
    },
    {
        "id": 2,
        "hookah_image": "http://127.0.0.1:8000/hookahImages/kalyannaya-zmist-kiev-vxod-pushkinskoy-1024x768.jpeg"
    }
]

}

React part:

class HookahDetail extends Component{

render(){
    const obj = this.props.hookahDetail;
    
    return(
        // TODO move style to css
        <div style = {{ color: "yellow", border: "1px solid yellow"  }}>
            <h4>{obj.hookah_name}</h4>
            <h5>
                    <p>{obj.city}</p>
                    {obj.street}
                    <p>{obj.hookah_style}</p>
                    <p>{obj.phone}</p>
                    Tobacco: 
                    <div>
                        
                    </div>
                    <p>{obj.description}</p>
                    <p>{obj.credit_card}</p>
                    <p>{obj.summer_terrace}</p>
                    <div>
                        {/* here is some mistake */}
                        {obj.hookah_tobacco.map((t) => {
                            return (
                                <div>{t.hookah_tobacco}</div>
                            )
                        })}
                    </div>
            </h5>
        </div>
    )
}

}

Error part:

TypeError: obj.hookah_tobacco is undefined

Console log part when {console.log(obj.hookah_tobacco)}():

0: Object { hookah_tobacco: "Al-Fakher" }

​ 1: Object { hookah_tobacco: "Serbetli" }

I can't understand why map() function does not work.

1
  • This is weird. try to log obj and obj.hookah_tobacco Commented Apr 1, 2021 at 21:18

1 Answer 1

1

Try to use it like this. This way can handle the undefined error

...
    {obj.hookah_tobacco ? obj.hookah_tobacco.map((t) => {
                    return (
                        <div>{t.hookah_tobacco}</div>
                    )
                }) : null}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.