\$\begingroup\$
\$\endgroup\$
Below is an implementation of a React app printing list. Are there any areas of improvement/suggestions in below code base
class ListElement extends React.PureComponent {
render() {
return <li onClick={() => this.props.handleClick(this.props.index)}>{this.props.item.text}</li>;
}
}
class ListComponent extends React.Component {
handleClick(index) {
this.props.onClick(index);
}
render() {
const listDetails = this.props.listDetails;
let height,width;
if (listDetails.hasOwnProperty("size")) {
height = listDetails.size.height;
width = listDetails.size.width;
}
return (
<ul style={{ height: height, width }}>
{this.props.items.map((item, i) => <ListElement item={item} key={i} index={i} handleClick={this.handleClick.bind(this)}/>)}
</ul>
);
}
}
ListComponent.propTypes = {
items: PropTypes.arrayOf(PropTypes.shape({
text: PropTypes.string.isRequired
})).isRequired,
listDetails: PropTypes.object.isRequired
};
200_success
145k22 gold badges190 silver badges478 bronze badges
1 Answer 1
\$\begingroup\$
\$\endgroup\$
- Use function syntax/memo when possible
- Use destructuring
- Use object literal shorthand
- Define defaults for
width
andheight
handleClick
is justonClick
renamed- Use tooling for formatting your code (eslint, prettier)
- Prefer ternary over if (not always true)
- Have a well defined API for your components (ListElement needs text, not the entire item, and doesn't really need index)
const ListElement = React.Memo(({ handleClick, label }) => (
<li onClick={handleClick()}>{label}</li>
));
const ListComponent = React.Memo(
({
items,
listDetails: {
size: { height, width }
},
onClick
}) => (
<ul style={{ height, width }}>
{items.map(({ text }, i) => (
<ListElement label={text} key={i} handleClick={() => onClick(i)} />
))}
</ul>
)
);
ListComponent.propTypes = {
items: PropTypes.arrayOf(
PropTypes.shape({
text: PropTypes.string.isRequired
})
).isRequired,
listDetails: PropTypes.object.isRequired
};
// Not quite sure I'm setting defaultProps correctly here, but you get the idea
ListComponent.defaultProps = {
listDetails: { size: { height: DEFAULT_HEIGHT, width: DEFAULT_WIDTH } }
};
You can also update propTypes
with the shape of listDetails
or change so that ListComponent
takes size
as an attribute instead, depending on what makes sense in your scenario.
default