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
    };
\$\endgroup\$
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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.