React Context example

Minimal example of Context

by jonahe

HTML

<script src="https://unpkg.com/[email protected]/dist/react-with-addons.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>
<div id="root"></div>

CSS

pre {
  display: inline-block;
  padding: 1px 3px;
  background-color: #e9e9e9;
  margin: 2px;
}

li.author {
  font-weight: bold;
}

Babel + JSX

const messages = [
	{ authorId: 1, message: 'Hello!', firstName: 'Sverker', lastName: 'Sverkerson'},
  { authorId: 2, message: 'Hi there!', firstName: 'Stina', lastName: 'Stinason'}, 
  { authorId: 3, message: 'Ok if I join too?', firstName: 'Lova', lastName: 'Lovason'}, 
  { authorId: 2, message: 'Sure!', firstName: 'Stina', lastName: 'Stinason'}
];
// Used to simulate being logged in as a specific user
const currentlyLoggedInAs = { id: 2 };

// In Functional components, the second argument is the context.
const Message = (props, context) => {
  const {authorId, message, firstName, lastName} = props.data;
  
  const isAuthor = authorId ===  context.loggedInAs.id;
  const fullName = firstName + ' ' + lastName;
  return (
    <li className={ isAuthor ? 'author' : ''}>"{ message }" - { isAuthor ? 'You' : fullName }</li>
  );
}
// NEEDED:  
// Specifies that this component will get context.loggedInAs passed down to it
Message.contextTypes = { loggedInAs: React.PropTypes.object }



// In Class components, the context can be accessed via this.contex
class MessageList extends React.Component {
	render() {
  	return (
      <div>
        <h2>Messages</h2>
        <ul>
          {this.props.children}
        </ul>
        <br/>
        <div>
          In { `<MessageList/>`} <pre>this.context</pre> still doesn't show 
          any sign of <pre>this.context.loggedInAs</pre> because we only specified 
          that we were interested in <pre>this.context.someOtherValue</pre>. So <pre>this.context</pre> is just: <br/>
          <pre>{ JSON.stringify(this.context, null, 2) }</pre>
        </div>
      </div>
   	);
  }
};
MessageList.contextTypes = { someOtherValue: React.PropTypes.string };


class App extends React.Component {
	// NEEDED: this determines what the child components will 
  // get when they access this.context.somePropertyName
	getChildContext() {
  	return { 
    	loggedInAs: this.props.loggedInUser, 
      someOtherValue: 'green' 
    };
  }
  
  render()...