Michaël Y. Michaël Y. - 2 months ago 21
React JSX Question

Best structure for a React component?

I would like to know what is the best structure and best practice the React component for you ? (With redux).

Thanks !

Answer

As a starter for 10:

I always ensure props, className and children are always treated in the same way.

  • the class name is always appended to any internal class names
  • children are always rendered if provided
  • any unused props are always attached to the parent div using the spread operator

This ensure all components are very flexible for future use as any extra attributes will always be added even if you hadn't coded for them.

import React from 'react';
import bemHelper from 'react-bem-helper';

import './styles.scss';

const bem = bemHelper({prefix: 'n-', name: 'button'});

export default class Button extends React.Component {

  constructor(props) {
    super(props);
  }

  static propTypes = {
    className: React.PropTypes.string,
    secondary: React.PropTypes.bool,
    href: React.PropTypes.string
  };

  static defaultProps = {
    secondary: false
  };

  render() {
    const {className, secondary, children, ...props} = this.props;

    const classes = bem(null, {
      'secondary': secondary,
      'primary': !secondary
    },
      className
    );
    const tag = this.props.href ? 'a' : 'button';
    return React.createElement(tag, {...classes, ...props}, children);
  }
}

a great project for you to take a look at, especially as far as adding redux goes is react-lego. It has a redux branch there showing you the code changes needed to turn a normal container/component into a redux component.