DEV Community

Azriz Jasni
Azriz Jasni

Posted on

Inspect Stateless Component Props in ReactJs

Hi, recently I've shared my tips in javascript, checkout here. On the last section, I did mention how do you debug using console.log.

So today, I'm going to share a little bit the same concept but it will be in ReactJs context. I hope it will useful for us 😊.

In my previous post, you can log current params of a callback function with
console.log(data) || ...someFn()

   const nameAndEmails = users.map((user) => console.log(user) || ({ 
    name: user.name, 
    email: user.email 
   }))
Enter fullscreen mode Exit fullscreen mode

In ReactJs, especially for stateless components, sometime our coworker didn't write any PropTypes. Hence, it a little bit hard to know what kind of props shape it will receive.

Lets jump to the example:

// let say you have this kind of component
const Button = (props) => (
    <button class="btn btn-primary" type="button" {...props} >
        {`${props.children}`}    
    </button>
);

// use it like this 
<Button type="Submit">Click Me</Button>
Enter fullscreen mode Exit fullscreen mode

You would not want to convert this component into { ... return (); }, because it requires a lot of typing, like this:

// 😓, need to type aloot of things here
const Button = (props) => {
    console.log(props);

    return (
        <button class="btn btn-primary" type="button" {...props} >    
           {`${props.children}`}
        </button>
    );
};
Enter fullscreen mode Exit fullscreen mode

So, instead of convert to ordinary function, you can try this approach to log the props.

const Button = (props) => console.log(props) || (
     <button class="btn btn-primary" type="button" {...props}>
        {`${props.children}`}
     </button>
);

// It will logs: 
// { 
//    type: 'Submit',
//    children: 'Click Me'
// }
Enter fullscreen mode Exit fullscreen mode

Essentially, you can use this trick to any callback function like in map., .filter, .reduce

I hope you get the idea, See you next time.

Latest comments (0)