Skip to content

Instantly share code, notes, and snippets.

@benhughes
Last active March 19, 2018 13:03
Show Gist options
  • Star 34 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save benhughes/7d28c15b7b03c9c5df83 to your computer and use it in GitHub Desktop.
Save benhughes/7d28c15b7b03c9c5df83 to your computer and use it in GitHub Desktop.

#A brief intro into Stateless functions#

So stateless functions are new in React 0.14 which are quite interesting. They look a bit like this.

const Test = ({name, amount}) => {
 return <div className="test">{name} has £{amount}</div>;
};

ReactDOM.render(<Test name="ben" amount="-2000" />) //  <div className="test">ben has £-200</div> 

They make simple components even simpler meaning the lazy no longer have to write prop types and render functions etc.. Hooray!

I'm sure many people will start using them for very simple components like buttons etc. but you can also do some crazier things like this:

class List extends Component {
  static subComponents = {
    list: ({items}) => <ul>{items.map(item => <List.subComponents.listItem item={item}/>)}</ul>,
    listItem: ({item}) => <li key={item}>{item}</li>
  };

  render() {
    const {myList} = this.props;
    
    return (
      <div className="some-holder">
        <List.subComponents.list items={myList} />        
      </div>
    );
  }
}

That's right! Inlining parts of your component instead of creating functions. Not entirely convinced it looks cleaner though (or if it's even useful), but I'm looking forward to playing around with them as the next project ramps up.

edit:

Actually after playing around with it it actually seems alot better to do something like this:

class MyComponent extends Component {
  static Button ({onClick, children}) {
    return (
      <button onClick={onClick}>
        {children}
      </button>
    );    
  }
  render() {
    const {onClick} = this.props;

    return (
      <div className="some-holder">
        <MyComponent.Button onClick={onClick} >
          Some Text
        </MyComponent.Button>
      </div>
    );
  }
}

Removing the need for functions such as renderButton().

@nmn
Copy link

nmn commented Sep 25, 2015

This:

const Test = ({name, amount}) => {
  return <div className="test">{name} has £{amount}</div>;
};

can be:

const Test = ({name, amount}) =>
  <div className="test">{name} has £{amount}</div>

but I would say using a named function is the best option as it sets function.name and will be better for debugging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment