Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

console.log inside a map in react component

Tags:

reactjs

I have a react component, and I need debug the value of 'customer' element that 'map' produce "customers.map( customer =>".

I've tried before "" this

{ console.log (customer)}

but i get error, here the component:

const CustomersList = ({ data: {loading, error, customers }}) => {
    if (loading) {
        return <p style={{color:"red"}}>Loading ...</p>;
    }
    if (error) {
        return <p>{error.message}</p>;
    }

    return (
        <div>
            Customers List
            { customers.map( customer =>
                (<div  key={customer.id} >Hey {customer.firstname}</div>)
            )}
        </div>
    );
};
like image 376
DDave Avatar asked Sep 06 '17 08:09

DDave


People also ask

How do I use the console log in maps?

Use {} with arrow function for block body and put the console. log inside that, with block body you need to use return to return the ui elements. As per MDN DOC: Arrow functions can have either a "concise body" or the usual "block body".

How do I add a console log in React?

Logging in React log() a value in React. If you want to continue logging a value every time the component re-renders, you should put the console. log() method under render() call.


1 Answers

Use {} with arrow function for block body and put the console.log inside that, with block body you need to use return to return the ui elements.

Like this:

{ 
    customers.map( customer => {
        console.log(customer);
        return <div  key={customer.id} >Hey {customer.firstname}</div>
    })
}

As per MDN DOC:

Arrow functions can have either a "concise body" or the usual "block body".

In a concise body, only an expression is needed, and an implicit return is attached. In a block body, you must use an explicit return statement.

Example:

var func = x => x * x;                  
// concise syntax, implied "return"

var func = (x, y) => { return x + y; }; 
// with block body, explicit "return" needed
like image 198
Mayank Shukla Avatar answered Sep 30 '22 10:09

Mayank Shukla