Inspect Stateless Component Props in ReactJs
Azriz Jasni
Posted on November 17, 2018
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
}))
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>
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>
);
};
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'
// }
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.
Posted on November 17, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.