3
\$\begingroup\$

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
asked Aug 5, 2019 at 12:52
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$
  • Use function syntax/memo when possible
  • Use destructuring
  • Use object literal shorthand
  • Define defaults for width and height
  • handleClick is just onClick 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.

answered Aug 5, 2019 at 17:13
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.