vendredi 6 septembre 2019

How to put condition IF ELSE inside .map in React JS

I am new to React Js. IF ELSE condition inside the map gives me error.

I want to put IF ELSE condition inside map. I don't want to use Ternary Operator if IF ELSE is possible.

class Home extends Component {

    constructor(props){
        //codes
    }

    testFunction = () => {
        //postDetails is something fetch from the server

        let tableDetail;
        tableDetail = Object.keys(postDetails).map((i) => (
            let val;

            /* I dont know how to achieve this part  */
            if(typeof postDetails[i].comment ===  'string'){
                val = <div>A String!</div>
            }else{
                val = <div>Not a string!</div>
            }
            /* I dont know how to achieve this part  */

            <>
                {val}
                // other codes ..
            </>;
        ));

        return tableDetail;
    }

    render() {

        return (
            <>
            <h3>Table</h3>
                {this.testFunction}
            </>
        )
    }

Aucun commentaire:

Enregistrer un commentaire