Adding functionality to stateless functions

 

Creating lots of small stateless functions in React is an excellent way to simplify your app.  A stateless function (in React) is basically a render method that it is returned from a function like so:

const DisplayName = (props) => {
  return (
    <span>{props.name}</span>
  );
};

<DisplayName name= "Shane"/>

In traditional React syntax it would look like this:

const DisplayName = React.createClass({
  render(){
    return (
      <span>{this.props.name}</span>
    );
  }
});

There are a couple of tricks to greatly expand the functionality you can deliver in these simple functions.

 

Destructuring Props allows you to explicitly list the props that are used by your component as well as making it easier for you and your IDE to identify unused variables.

const DisplayName = ({name}) => {
  return (
    <span>{name}</span>
  );
};

<DisplayName name= "Shane"/>

 

Use Higher Order Functions to make adding functionality to your components a breeze. Here we are using one to call preventDefault on an event and pass props down to the  onClick function.

const createPreventedEventFunc = (func, props) => (e) => {
  e.preventDefault();
  return func(e, props);
};

const DisplayName = ({onClick, name, ...props}) => {
  return (
    <a onClick={createPreventedEventFunc(onClick, {name, ...props})}>{name}</a>
  );
};

<DisplayName name="Shane" onClick={(e, props) => console.log(props.name)}/>

 

If you use react-redux you can use connect combined with mapStateToProps and  mapDispatchToProps to inject state and dispatched functions into a stateless function’s props.

const createPreventedEventFunc = (func, props) => (e) => {
  e.preventDefault();
  return func(e, props);
};

const DisplayName = ({onClick, name, ...props}) => {
  return (
    <a onClick={createPreventedEventFunc(onClick, {name, ...props})}>{name}</a>
  );
};

const mapStateToProps = (state) => {
  return {
    name: state.AccountState.user.fullName
  }
};

const mapDispatchToProps = (dispatch) => {
  return {
    onClick: (e, {name}) => {
      dispatch({
        type: "CLICKED_NAME",
        payload: name
      });
    }
  }
};

const ConnectedDisplayName = connect(mapStateToProps, mapDispatchToProps)(DisplayName);

<ConnectedDisplayName/>

 

Filed under:   codinglife   functionalprogramming   javascript   react