{

  "name": "React",
  "order": 5,
  "time": "5 hours",
  "helpRoom": "Help",
  "required": [
    {
      "src": "https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react.js"
    },
    {
      "src": "https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react-dom.js"
    }
  ],
  "template": "<body><div id='root'></div><div id='challenge-node'></div>${ source }</body>",
  "challenges": [
    {
      "id": "587d7dbc367417b2b2512bb1",
      "title": "Create a Simple JSX Element",
      "releasedOn": "December 25, 2017",
      "description": [
        "<strong>Intro:</strong> React is an Open Source view library created and maintained by Facebook. It's a great tool to render the User Interface (UI) of modern web applications.",
        "React uses a syntax extension of JavaScript called JSX that allows you to write HTML directly within JavaScript. This has several benefits. It lets you use the full programmatic power of JavaScript within HTML, and helps to keep your code readable. For the most part, JSX is similar to the HTML that you have already learned, however there are a few key differences that will be covered throughout these challenges.",
        "For instance, because JSX is a syntactic extension of JavaScript, you can actually write JavaScript directly within JSX. To do this, you simply include the code you want to be treated as JavaScript within curly braces: <code>{ 'this is treated as JavaScript code' }</code>. Keep this in mind, since it's used in several future challenges.",
        "However, because JSX is not valid JavaScript, JSX code must be compiled into JavaScript. The transpiler Babel is a popular tool for this process. For your convenience, it's already added behind the scenes for these challenges. If you happen to write syntactically invalid JSX, you will see the first test in these challenges fail.",
        "<hr>",
        "<strong>Instructions:</strong> The current code uses JSX to assign a <code>div</code> element to the constant <code>JSX</code>. Replace the <code>div</code> with an <code>h1</code> element and add the text <code>Hello JSX!</code> inside it."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "",
            "const JSX = <div></div>;",
            ""
          ],
          "tail": "ReactDOM.render(JSX, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert(JSX.type === 'h1', 'message: The constant <code>JSX</code> should return an <code>h1</code> element.');",
        "assert(Enzyme.shallow(JSX).contains('Hello JSX!'), 'message: The <code>h1</code> tag should include the text <code>Hello JSX!</code>');"
      ],
      "solutions": [
        "const JSX = <h1>Hello JSX!</h1>;"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24bbe0dba28a8d3cbd4c5d",
      "title": "Create a Complex JSX Element",
      "releasedOn": "December 25, 2017",
      "description": [
        "The last challenge was a simple example of JSX, but JSX can represent more complex HTML as well.",
        "One important thing to know about nested JSX is that it must return a single element.",
        "This one parent element would wrap all of the other levels of nested elements.",
        "For instance, several JSX elements written as siblings with no parent wrapper element will not transpile.",
        "Here's an example:",
        "<b>Valid JSX:</b>",
        "<blockquote>&lt;div&gt;<br>  &lt;p&gt;Paragraph One&lt;/p&gt;<br>  &lt;p&gt;Paragraph Two&lt;/p&gt;<br>  &lt;p&gt;Paragraph Three&lt;/p&gt;<br>&lt;/div&gt;</blockquote>",
        "<b>Invalid JSX:</b>",
        "<blockquote>&lt;p&gt;Paragraph One&lt;/p&gt;<br>&lt;p&gt;Paragraph Two&lt;/p&gt;<br>&lt;p&gt;Paragraph Three&lt;/p&gt;<br></blockquote>",
        "<hr>",
        "Define a new constant <code>JSX</code> that renders a <code>div</code> which contains the following elements in order:",
        "An <code>h1</code>, a <code>p</code>, and an unordered list that contains three <code>li</code> items. You can include any text you want within each element.",
        "<strong>Note:</strong>&nbsp;When rendering multiple elements like this, you can wrap them all in parentheses, but it's not strictly required. Also notice this challenge uses a <code>div</code> tag to wrap all the child elements within a single parent element. If you remove the <code>div</code>, the JSX will no longer transpile. Keep this in mind, since it will also apply when you return JSX elements in React components."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "// write your code here",
            ""
          ],
          "tail": "ReactDOM.render(JSX, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert(JSX.type === 'div', 'message: The constant <code>JSX</code> should return a <code>div</code> element.');",
        "assert(JSX.props.children[1].type === 'p', 'message: The <code>div</code> should contain a <code>p</code> tag as the second element.');",
        "assert(JSX.props.children[2].type === 'ul', 'message: The <code>div</code> should contain a <code>ul</code> tag as the third element.');",
        "assert(JSX.props.children[0].type === 'h1', 'message: The <code>div</code> should contain an <code>h1</code> tag as the first element.');",
        "assert(JSX.props.children[2].props.children.length === 3, 'message: The <code>ul</code> should contain three <code>li</code> elements.');"
      ],
      "solutions": [
        "const JSX = (\n<div>\n  <h1>Hello JSX!</h1>\n  <p>Some info</p>\n  <ul>\n    <li>An item</li>\n    <li>Another item</li>\n    <li>A third item</li>\n  </ul>\n</div>);"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24bbe0dba28a8d3cbd4c5e",
      "title": "Add Comments in JSX",
      "releasedOn": "December 25, 2017",
      "description": [
        "JSX is a syntax that gets compiled into valid JavaScript. Sometimes, for readability, you might need to add comments to your code. Like most programming languages, JSX has its own way to do this.",
        "To put comments inside JSX, you use the syntax <code>{/* */}</code> to wrap around the comment text.",
        "<hr>",
        "The code editor has a JSX element similar to what you created in the last challenge. Add a comment somewhere within the provided <code>div</code> element, without modifying the existing <code>h1</code> or <code>p</code> elements."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "const JSX = (",
            "  <div>",
            "    <h1>This is a block of JSX</h1>",
            "    <p>Here's a subtitle</p>",
            "  </div>",
            ");"
          ],
          "tail": "ReactDOM.render(JSX, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert(JSX.type === 'div', 'message: The constant <code>JSX</code> should return a <code>div</code> element.');",
        "assert(JSX.props.children[0].type === 'h1', 'message: The <code>div</code> should contain an <code>h1</code> tag as the first element.');",
        "assert(JSX.props.children[1].type === 'p', 'message: The <code>div</code> should contain a <code>p</code> tag as the second element.');",
        "getUserInput => assert(getUserInput('index').includes('/*') && getUserInput('index').includes('*/'), 'message: The <code>JSX</code> should include a comment.');"
      ],
      "solutions": [
        "const JSX = (\n<div>\n  <h1>This is a block of JSX</h1>\n  { /* this is a JSX comment */ }\n  <p>Here's a subtitle</p>\n</div>);"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24bbe0dba28a8d3cbd4c5f",
      "title": "Render HTML Elements to the DOM",
      "releasedOn": "December 25, 2017",
      "description": [
        "So far, you've learned that JSX is a convenient tool to write readable HTML within JavaScript. With React, we can render this JSX directly to the HTML DOM using React's rendering API known as ReactDOM.",
        "ReactDOM offers a simple method to render React elements to the DOM which looks like this: <code>ReactDOM.render(componentToRender, targetNode)</code>, where the first argument is the React element or component that you want to render, and the second argument is the DOM node that you want to render the component to.",
        "As you would expect, <code>ReactDOM.render()</code> must be called after the JSX element declarations, just like how you must declare variables before using them.",
        "<hr>",
        "The code editor has a simple JSX component. Use the <code>ReactDOM.render()</code> method to render this component to the page. You can pass defined JSX elements directly in as the first argument and use <code>document.getElementById()</code> to select the DOM node to render them to. There is a <code>div</code> with <code>id='challenge-node'</code> available for you to use. Make sure you don't change the <code>JSX</code> constant."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "const JSX = (",
            "  <div>",
            "    <h1>Hello World</h1>",
            "    <p>Lets render this to the DOM</p>",
            "  </div>",
            ");",
            "// change code below this line",
            ""
          ]
        }
      },
      "tests": [
        "assert(JSX.type === 'div', 'message: The constant <code>JSX</code> should return a <code>div</code> element.');",
        "assert(JSX.props.children[0].type === 'h1', 'message: The <code>div</code> should contain an <code>h1</code> tag as the first element.');",
        "assert(JSX.props.children[1].type === 'p', 'message: The <code>div</code> should contain a <code>p</code> tag as the second element.');",
        "assert(document.getElementById('challenge-node').childNodes[0].innerHTML === '<h1>Hello World</h1><p>Lets render this to the DOM</p>', 'message: The provided JSX element should render to the DOM node with id <code>challenge-node</code>.');"
      ],
      "solutions": [
        "const JSX = (\n<div>\n  <h1>Hello World</h1>\n  <p>Lets render this to the DOM</p>\n</div>\n);\n// change code below this line\nReactDOM.render(JSX, document.getElementById('challenge-node'));"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036160",
      "title": "Define an HTML Class in JSX",
      "releasedOn": "December 25, 2017",
      "description": [
        "Now that you're getting comfortable writing JSX, you may be wondering how it differs from HTML.",
        "So far, it may seem that HTML and JSX are exactly the same.",
        "One key difference in JSX is that you can no longer use the word <code>class</code> to define HTML classes. This is because <code>class</code> is a reserved word in JavaScript. Instead, JSX uses <code>className</code>.",
        "In fact, the naming convention for all HTML attributes and event references in JSX become camelCase. For example, a click event in JSX is <code>onClick</code>, instead of <code>onclick</code>. Likewise, <code>onchange</code> becomes <code>onChange</code>. While this is a subtle difference, it is an important one to keep in mind moving forward.",
        "<hr>",
        "Apply a class of <code>myDiv</code> to the <code>div</code> provided in the JSX code."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "const JSX = (",
            "  <div>",
            "    <h1>Add a class to this div</h1>",
            "  </div>",
            ");"
          ],
          "tail": "ReactDOM.render(JSX, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert.strictEqual(JSX.type, 'div', 'message: The constant <code>JSX</code> should return a <code>div</code> element.');",
        "assert.strictEqual(JSX.props.className, 'myDiv', 'message: The <code>div</code> has a class of <code>myDiv</code>.');"
      ],
      "solutions": [
        "const JSX = (\n<div className = 'myDiv'>\n  <h1>Add a class to this div</h1>\n</div>);"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036161",
      "title": "Learn About Self-Closing JSX Tags",
      "releasedOn": "December 25, 2017",
      "description": [
        "So far, you’ve seen how JSX differs from HTML in a key way with the use of <code>className</code> vs. <code>class</code> for defining HTML classes.",
        "Another important way in which JSX differs from HTML is in the idea of the self-closing tag.",
        "In HTML, almost all tags have both an opening and closing tag: <code>&lt;div&gt;&lt;/div&gt;</code>; the closing tag always has a forward slash before the tag name that you are closing. However, there are special instances in HTML called “self-closing tags”, or tags that don’t require both an opening and closing tag before another tag can start.",
        "For example the line-break tag can be written as <code>&lt;br&gt;</code> or as <code>&lt;br /&gt;</code>, but should never be written as <code>&lt;br&gt;&lt;/br&gt;</code>, since it doesn't contain any content.",
        "In JSX, the rules are a little different. Any JSX element can be written with a self-closing tag, and every element must be closed. The line-break tag, for example, must always be written as <code>&lt;br /&gt;</code> in order to be valid JSX that can be transpiled. A <code>&lt;div&gt;</code>, on the other hand, can be written as <code>&lt;div /&gt;</code> or <code>&lt;div&gt;&lt;/div&gt;</code>. The difference is that in the first syntax version there is no way to include anything in the <code>&lt;div /&gt;</code>. You will see in later challenges that this syntax is useful when rendering React components.",
        "<hr>",
        "Fix the errors in the code editor so that it is valid JSX and successfully transpiles. Make sure you don't change any of the content - you only need to close tags where they are needed."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "const JSX = (",
            "  <div>",
            "    {/* remove comment and change code below this line",
            "    <h2>Welcome to React!</h2> <br >",
            "    <p>Be sure to close all tags!</p>",
            "    <hr >",
            "    remove comment and change code above this line */}",
            "  </div>",
            ");",
            ""
          ],
          "tail": "ReactDOM.render(JSX, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert.strictEqual(JSX.type, 'div', 'message: The constant <code>JSX</code> should return a <code>div</code> element.');",
        "assert(Enzyme.shallow(JSX).find('br').length === 1, 'message: The <code>div</code> should contain a <code>br</code> tag.');",
        "assert(Enzyme.shallow(JSX).find('hr').length === 1, 'message: The <code>div</code> should contain an <code>hr</code> tag.');"
      ],
      "solutions": [
        "const JSX = (\n<div>\n  {/* change code below this line */}\n  <h2>Welcome to React!</h2> <br />\n  <p>Be sure to close all tags!</p>\n  <hr />\n  {/* change code above this line */}\n</div>\n);"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036162",
      "title": "Create a Stateless Functional Component",
      "releasedOn": "December 25, 2017",
      "description": [
        "Components are the core of React. Everything in React is a component and here you will learn how to create one.",
        "There are two ways to create a React component. The first way is to use a JavaScript function. Defining a component in this way creates a <em>stateless functional component</em>. The concept of state in an application will be covered in later challenges. For now, think of a stateless component as one that can receive data and render it, but does not manage or track changes to that data. (We'll cover the second way to create a React component in the next challenge.)",
        "To create a component with a function, you simply write a JavaScript function that returns either JSX or <code>null</code>. One important thing to note is that React requires your function name to begin with a capital letter. Here's an example of a stateless functional component that assigns an HTML class in JSX:",
        "<blockquote>// After being transpiled, the &lt;div&gt; will have a CSS class of 'customClass'<br>const DemoComponent = function() {<br>  return (<br>    &lt;div className='customClass' /&gt;<br>  );<br>};</blockquote>",
        "Because a JSX component represents HTML, you could put several components together to create a more complex HTML page. This is one of the key advantages of the component architecture React provides. It allows you to compose your UI from many separate, isolated components. This makes it easier to build and maintain complex user interfaces.",
        "<hr>",
        "The code editor has a function called <code>MyComponent</code>. Complete this function so it returns a single <code>div</code> element which contains some string of text.",
        "<strong>Note:</strong>&nbsp;The text is considered a child of the <code>div</code> element, so you will not be able to use a self-closing tag."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "const MyComponent = function() {",
            "  // change code below this line",
            "",
            "",
            "",
            "  // change code above this line",
            "}"
          ],
          "tail": "ReactDOM.render(<MyComponent />, document.getElementById('root'))" }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.length === 1; })(), 'message: <code>MyComponent</code> should return JSX.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.children().type() === 'div' })(), 'message: <code>MyComponent</code> should return a <code>div</code> element.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.find('div').text() !== ''; })(), 'message: The <code>div</code> element should contain a string of text.');"
      ],
      "solutions": [
        "\nconst MyComponent = function() {\n  // change code below this line\n  return (\n    <div>\n      Demo Solution\n    </div>\n  );\n  // change code above this line\n}"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036163",
      "title": "Create a React Component",
      "releasedOn": "December 25, 2017",
      "description": [
        "The other way to define a React component is with the ES6 <code>class</code> syntax. In the following example, <code>Kitten</code> extends <code>React.Component</code>:",
        "<blockquote>class Kitten extends React.Component {<br>  constructor(props) {<br>    super(props);<br>  }<br><br>  render() {<br>    return (<br>      &lt;h1&gt;Hi&lt;/h1&gt;<br>    );<br>  }<br>}</blockquote>",
        "This creates an ES6 class <code>Kitten</code> which extends the <code>React.Component</code> class. So the <code>Kitten</code> class now has access to many useful React features, such as local state and lifecycle hooks. Don't worry if you aren't familiar with these terms yet, they will be covered in greater detail in later challenges.",
        "Also notice the <code>Kitten</code> class has a <code>constructor</code> defined within it that calls <code>super()</code>. It uses <code>super()</code> to call the constructor of the parent class, in this case <code>React.Component</code>. The constructor is a special method used during the initialization of objects that are created with the <code>class</code> keyword. It is best practice to call a component's <code>constructor</code> with <code>super</code>, and pass <code>props</code> to both. This makes sure the component is initialized properly. For now, know that it is standard for this code to be included. Soon you will see other uses for the constructor as well as <code>props</code>.",
        "<hr>",
        "<code>MyComponent</code> is defined in the code editor using class syntax. Finish writing the <code>render</code> method so it returns a <code>div</code> element that contains an <code>h1</code> with the text <code>Hello React!</code>."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "",
            "class MyComponent extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "  }",
            "  render() {",
            "    // change code below this line",
            "",
            "",
            "",
            "    // change code above this line",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<MyComponent />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert(Enzyme.shallow(React.createElement(MyComponent)).type() === 'div', 'message: The React component should return a <code>div</code> element.');",
        "assert(/<div><h1>.*<\\/h1><\\/div>/.test(Enzyme.shallow(React.createElement(MyComponent)).html()), 'message: The returned <code>div</code> should render an <code>h1</code> header within it.');",
        "assert(Enzyme.shallow(React.createElement(MyComponent)).html() === '<div><h1>Hello React!</h1></div>', 'message: The <code>h1</code> header should contain the string <code>Hello React!</code>.');"
      ],
      "solutions": [
        "\nclass MyComponent extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n  render() {\n    // change code below this line\n    return (\n      <div>\n        <h1>Hello React!</h1>\n      </div>\n    );\n    // change code above this line\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036164",
      "title": "Create a Component with Composition",
      "releasedOn": "December 25, 2017",
      "description": [
        "Now we will look at how we can compose multiple React components together. Imagine you are building an App and have created three components, a <code>Navbar</code>, <code>Dashboard</code>, and <code>Footer</code>.",
        "To compose these components together, you could create an <code>App</code> <i>parent</i> component which renders each of these three components as <i>children</i>. To render a component as a child in a React component, you include the component name written as a custom HTML tag in the JSX. For example, in the <code>render</code> method you could write:",
        "<blockquote>return (<br> &lt;App&gt;<br>  &lt;Navbar /&gt;<br>  &lt;Dashboard /&gt;<br>  &lt;Footer /&gt;<br> &lt;/App&gt;<br>)</blockquote>",
        "When React encounters a custom HTML tag that references another component (a component name wrapped in <code>&lt; /&gt;</code> like in this example), it renders the markup for that component in the location of the tag. This should illustrate the parent/child relationship between the <code>App</code> component and the <code>Navbar</code>, <code>Dashboard</code>, and <code>Footer</code>.",
        "<hr>",
        "In the code editor, there is a simple functional component called <code>ChildComponent</code> and a React component called <code>ParentComponent</code>. Compose the two together by rendering the <code>ChildComponent</code> within the <code>ParentComponent</code>. Make sure to close the <code>ChildComponent</code> tag with a forward slash.",
        "<strong>Note:</strong>&nbsp;<code>ChildComponent</code> is defined with an ES6 arrow function because this is a very common practice when using React. However, know that this is just a function. If you aren't familiar with the arrow function syntax, please refer to the JavaScript section."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "const ChildComponent = () => {",
            "  return (",
            "    <div>",
            "      <p>I am the child</p>",
            "    </div>",
            "  );",
            "};",
            "",
            "class ParentComponent extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "  }",
            "  render() {",
            "    return (",
            "      <div>",
            "        <h1>I am the parent</h1>",
            "        { /* change code below this line */ }",
            "",
            "",
            "        { /* change code above this line */ }",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<ParentComponent />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { var shallowRender = Enzyme.shallow(React.createElement(ParentComponent)); return shallowRender.type() === 'div'; })(), 'message: The React component should return a single <code>div</code> element.');",
        "assert((function() { var shallowRender = Enzyme.shallow(React.createElement(ParentComponent)); return shallowRender.children().length === 2; })(), 'message: The component should return two nested elements.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ParentComponent)); return mockedComponent.find('ParentComponent').find('ChildComponent').length === 1; })(), 'message: The component should return the ChildComponent as its second child.');"
      ],
      "solutions": [
        "const ChildComponent = () => {\n  return (\n    <div>\n      <p>I am the child</p>\n    </div>\n  );\n};\n\nclass ParentComponent extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n  render() {\n    return (\n      <div>\n        <h1>I am the parent</h1>\n        { /* change code below this line */ }\n        <ChildComponent />\n        { /* change code above this line */ }\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036165",
      "title": "Use React to Render Nested Components",
      "releasedOn": "December 25, 2017",
      "description": [
        "The last challenge showed a simple way to compose two components, but there are many different ways you can compose components with React.",
        "Component composition is one of React's powerful features. When you work with React, it is important to start thinking about your user interface in terms of components like the App example in the last challenge. You break down your UI into its basic building blocks, and those pieces become the components. This helps to separate the code responsible for the UI from the code responsible for handling your application logic. It can greatly simplify the development and maintenance of complex projects.",
        "<hr>",
        "There are two functional components defined in the code editor, called <code>TypesOfFruit</code> and <code>Fruits</code>. Take the <code>TypesOfFruit</code> component and compose it, or <em>nest</em> it, within the <code>Fruits</code> component. Then take the <code>Fruits</code> component and nest it within the <code>TypesOfFood</code> component. The result should be a child component, nested within a parent component, which is nested within a parent component of its own!"
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "const TypesOfFruit = () => {",
            "  return (",
            "    <div>",
            "      <h2>Fruits:</h2>",
            "      <ul>",
            "        <li>Apples</li>",
            "        <li>Blueberries</li>",
            "        <li>Strawberries</li>",
            "        <li>Bananas</li>",
            "      </ul>",
            "    </div>",
            "  );",
            "};",
            "",
            "const Fruits = () => {",
            "  return (",
            "    <div>",
            "      { /* change code below this line */ }",
            "",
            "      { /* change code above this line */ }",
            "    </div>",
            "  );",
            "};",
            "",
            "class TypesOfFood extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "  }",
            "",
            "  render() {",
            "    return (",
            "      <div>",
            "        <h1>Types of Food:</h1>",
            "        { /* change code below this line */ }",
            "",
            "        { /* change code above this line */ }",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<TypesOfFood />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert(Enzyme.shallow(React.createElement(TypesOfFood)).type() === 'div', 'message: The <code>TypesOfFood</code> component should return a single <code>div</code> element.');",
        "assert(Enzyme.shallow(React.createElement(TypesOfFood)).props().children[1].type.name === 'Fruits', 'message: The <code>TypesOfFood</code> component should return the <code>Fruits</code> component.');",
        "assert(Enzyme.mount(React.createElement(TypesOfFood)).find('h2').html() === '<h2>Fruits:</h2>', 'message: The <code>Fruits</code> component should return the <code>TypesOfFruit</code> component.');",
        "assert(Enzyme.mount(React.createElement(TypesOfFood)).find('ul').text() === 'ApplesBlueberriesStrawberriesBananas', 'message: The <code>TypesOfFruit</code> component should return the <code>h2</code> and <code>ul</code> elements.');"
      ],
      "solutions": [
        "const TypesOfFruit = () => {\n  return (\n    <div>\n      <h2>Fruits:</h2>\n      <ul>\n        <li>Apples</li>\n        <li>Blueberries</li>\n        <li>Strawberries</li>\n        <li>Bananas</li>\n      </ul>\n    </div>\n  );\n};\n\nconst Fruits = () => {\n  return (\n    <div>\n      { /* change code below this line */ }\n        <TypesOfFruit />\n      { /* change code above this line */ }\n    </div>\n  );\n};\n\nclass TypesOfFood extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n\n  render() {\n    return (\n      <div>\n        <h1>Types of Food:</h1>\n        { /* change code below this line */ }\n        <Fruits />\n        { /* change code above this line */ }\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036166",
      "title": "Compose React Components",
      "releasedOn": "December 25, 2017",
      "description": [
        "As the challenges continue to use more complex compositions with React components and JSX, there is one important point to note. Rendering ES6 style class components within other components is no different than rendering the simple components you used in the last few challenges. You can render JSX elements, stateless functional components, and ES6 class components within other components.",
        "<hr>",
        "In the code editor, the <code>TypesOfFood</code> component is already rendering a component called <code>Vegetables</code>. Also, there is the <code>Fruits</code> component from the last challenge.",
        "Nest two components inside of <code>Fruits</code> &mdash; first <code>NonCitrus</code>, and then <code>Citrus</code>. Both of these components are provided for you in the background. Next, nest the <code>Fruits</code> class component into the the <code>TypesOfFood</code> component, below the <code>h1</code> header and above <code>Vegetables</code>. The result should be a series of nested components, which uses two different component types."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "head": [
            "class NonCitrus extends React.Component {",
              "  render() {",
              "    return (",
              "      <div>",
              "        <h4>Non-Citrus:</h4>",
              "        <ul>",
              "          <li>Apples</li>",
              "          <li>Blueberries</li>",
              "          <li>Strawberries</li>",
              "          <li>Bananas</li>",
              "        </ul>",
              "      </div>",
              "    );",
              "  }",
              "};",
              "class Citrus extends React.Component {",
              "  render() {",
              "    return (",
              "      <div>",
              "        <h4>Citrus:</h4>",
              "        <ul>",
              "          <li>Lemon</li>",
              "          <li>Lime</li>",
              "          <li>Orange</li>",
              "          <li>Grapefruit</li>",
              "        </ul>",
              "      </div>",
              "    );",
              "  }",
              "};",
              "class Vegetables extends React.Component {",
              "  render() {",
              "    return (",
              "      <div>",
              "        <h2>Vegetables:</h2>",
              "        <ul>",
              "          <li>Brussel Sprouts</li>",
              "          <li>Broccoli</li>",
              "          <li>Squash</li>",
              "        </ul>",
              "      </div>",
              "    );",
              "     }",
              "};"
          ],
          "contents": [
            "class Fruits extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "  }",
            "  render() {",
            "    return (",
            "      <div>",
            "        <h2>Fruits:</h2>",
            "        { /* change code below this line */ }",
            "",
            "         { /* change code above this line */ }",
            "      </div>",
            "    );",
            "  }",
            "};",
            "",
            "class TypesOfFood extends React.Component {",
            "  constructor(props) {",
            "     super(props);",
            "  }",
            "  render() {",
            "    return (",
            "      <div>",
            "        <h1>Types of Food:</h1>",
            "        { /* change code below this line */ }",
            "",
            "        { /* change code above this line */ }",
            "        <Vegetables />",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<TypesOfFood />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().type() === 'div'; })(), 'message: The <code>TypesOfFood</code> component should return a single <code>div</code> element.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().childAt(1).name() === 'Fruits'; })(), 'message: The <code>TypesOfFood</code> component should return the <code>Fruits</code> component.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return (mockedComponent.find('Fruits').children().find('NonCitrus').length === 1 && mockedComponent.find('Fruits').children().find('Citrus').length === 1); })(), 'message: The <code>Fruits</code> component should return the <code>NonCitrus</code> component and the <code>Citrus</code> component.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().childAt(2).name() === 'Vegetables'; })(), 'message: The <code>TypesOfFood</code> component should return the <code>Vegetables</code> component below the <code>Fruits</code> component.');"
      ],
      "solutions": [
        "class Fruits extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n  render() {\n    return (\n      <div>\n        <h2>Fruits:</h2>\n        { /* change code below this line */ }\n        <NonCitrus />\n        <Citrus />\n        { /* change code above this line */ }\n      </div>\n    )\n  }\n}\n\nclass TypesOfFood extends React.Component {\n  constructor(props) {\n     super(props);\n  }\n    render() {\n      return (\n        <div>\n        <h1>Types of Food:</h1>\n          { /* change code below this line */ }\n          <Fruits />\n          { /* change code above this line */ }\n          <Vegetables />\n        </div>\n      );\n    }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036167",
      "title": "Render a Class Component to the DOM",
      "releasedOn": "December 25, 2017",
      "description": [
        "You may remember using the ReactDOM API in an earlier challenge to render JSX elements to the DOM. The process for rendering React components will look very similar. The past few challenges focused on components and composition, so the rendering was done for you behind the scenes. However, none of the React code you write will render to the DOM without making a call to the ReactDOM API.",
        "Here's a refresher on the syntax: <code>ReactDOM.render(componentToRender, targetNode)</code>. The first argument is the React component that you want to render. The second argument is the DOM node that you want to render that component within.",
        "React components are passed into <code>ReactDOM.render()</code> a little differently than JSX elements. For JSX elements, you pass in the name of the element that you want to render. However, for React components, you need to use the same syntax as if you were rendering a nested component, for example <code>ReactDOM.render(&lt;ComponentToRender /&gt;, targetNode)</code>. You use this syntax for both ES6 class components and functional components.",
        "<hr>",
        "Both the <code>Fruits</code> and <code>Vegetables</code> components are defined for you behind the scenes. Render both components as children of the <code>TypesOfFood</code> component, then render <code>TypesOfFood</code> to the DOM. There is a <code>div</code> with <code>id='challenge-node'</code> available for you to use."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "head": [
            "",
            "const Fruits = () => {",
              "  return (",
                "    <div>",
                "      <h2>Fruits:</h2>",
                "      <h4>Non-Citrus:</h4>",
                "        <ul>",
                "          <li>Apples</li>",
                "          <li>Blueberries</li>",
                "          <li>Strawberries</li>",
                "          <li>Bananas</li>",
                "        </ul>",
                "      <h4>Citrus:</h4>",
                "        <ul>",
                "          <li>Lemon</li>",
                "          <li>Lime</li>",
                "          <li>Orange</li>",
                "          <li>Grapefruit</li>",
                "        </ul>",
                "    </div>",
                "  );",
                "};",
                "const Vegetables = () => {",
                  "  return (",
                    "    <div>",
                    "      <h2>Vegetables:</h2>",
                    "      <ul>",
                    "        <li>Brussel Sprouts</li>",
                    "        <li>Broccoli</li>",
                    "        <li>Squash</li>",
                    "      </ul>",
                    "    </div>",
                    "  );",
                    "};",
                    ""
          ],
          "contents": [
            "",
            "class TypesOfFood extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "  }",
            "  render() {",
            "    return (",
            "      <div>",
            "        <h1>Types of Food:</h1>",
            "        {/* change code below this line */}",
            "",
            "        {/* change code above this line */}",
            "      </div>",
            "    );",
            "  }",
            "};",
            "",
            "// change code below this line",
            ""
          ]
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().type() === 'div'; })(), 'message: The <code>TypesOfFood</code> component should return a single <code>div</code> element.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().childAt(1).name() === 'Fruits'; })(), 'message: The <code>TypesOfFood</code> component should render the <code>Fruits</code> component after the <code>h1</code> element.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().childAt(2).name() === 'Vegetables'; })(), 'message: The <code>TypesOfFood</code> component should render the <code>Vegetables</code> component after <code>Fruits</code>.');",
        "assert((function() { const html = document.getElementById('challenge-node').childNodes[0].innerHTML; return (html === '<h1>Types of Food:</h1><div><h2>Fruits:</h2><h4>Non-Citrus:</h4><ul><li>Apples</li><li>Blueberries</li><li>Strawberries</li><li>Bananas</li></ul><h4>Citrus:</h4><ul><li>Lemon</li><li>Lime</li><li>Orange</li><li>Grapefruit</li></ul></div><div><h2>Vegetables:</h2><ul><li>Brussel Sprouts</li><li>Broccoli</li><li>Squash</li></ul></div>'); })(), 'message: The <code>TypesOfFood</code> component should render to the DOM within the <code>div</code> with the id <code>challenge-node</code>.');"
      ],
      "solutions": [
        "\nclass TypesOfFood extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n  render() {\n    return (\n      <div>\n        <h1>Types of Food:</h1>\n        {/* change code below this line */}\n          <Fruits />\n           <Vegetables />\n         {/* change code above this line */}\n      </div>\n    );\n  }\n};\n\n// change code below this line\nReactDOM.render(<TypesOfFood />, document.getElementById('challenge-node'));"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036168",
      "title": "Write a React Component from Scratch",
      "releasedOn": "December 25, 2017",
      "description": [
        "Now that you've learned the basics of JSX and React components, it's time to write a component on your own. React components are the core building blocks of React applications so it's important to become very familiar with writing them. Remember, a typical React component is an ES6 <code>class</code> which extends <code>React.Component</code>. It has a render method that returns HTML (from JSX) or <code>null</code>. This is the basic form of a React component. Once you understand this well, you will be prepared to start building more complex React projects.",
        "<hr>",
        "Define a class <code>MyComponent</code> that extends <code>React.Component</code>. Its render method should return a <code>div</code> that contains an <code>h1</code> tag with the text: <code>My First React Component!</code> in it. Use this text exactly, the case and punctuation matter. Make sure to call the constructor for your component, too.",
        "Render this component to the DOM using <code>ReactDOM.render()</code>. There is a <code>div</code> with <code>id='challenge-node'</code> available for you to use."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "// change code below this line",
            ""
          ]
        }
      },
      "tests": [
        "getUserInput => assert(getUserInput('index').replace(/\\s/g, '').includes('classMyComponentextendsReact.Component{'), 'message: There should be a React component called <code>MyComponent</code>.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.find('h1').text() === 'My First React Component!'; })(), 'message: <code>MyComponent</code> should contain an <code>h1</code> tag with text <code>My First React Component!</code> Case and punctuation matter.');",
        "assert(document.getElementById('challenge-node').childNodes.length === 1, 'message: <code>MyComponent</code> should render to the DOM.');"
      ],
      "solutions": [
        "// change code below this line\nclass MyComponent extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n  render() {\n    return (\n      <div>\n        <h1>My First React Component!</h1>\n      </div>\n    );\n  }\n};\n\nReactDOM.render(<MyComponent />, document.getElementById('challenge-node'));"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036169",
      "title": "Pass Props to a Stateless Functional Component",
      "releasedOn": "December 25, 2017",
      "description": [
        "The previous challenges covered a lot about creating and composing JSX elements, functional components, and ES6 style class components in React. With this foundation, it's time to look at another feature very common in React: <b>props</b>. In React, you can pass props, or properties, to child components. Say you have an <code>App</code> component which renders a child component called <code>Welcome</code> that is a stateless functional component. You can pass <code>Welcome</code> a <code>user</code> property by writing:",
        "<blockquote>&lt;App&gt;<br>  &lt;Welcome user='Mark' /&gt;<br>&lt;/App&gt;</blockquote>",
        "You use <strong>custom HTML attributes</strong> that React provides support for to pass the property <code>user</code> to the component <code>Welcome</code>. Since <code>Welcome</code> is a stateless functional component, it has access to this value like so:",
        "<blockquote>const Welcome = (props) => &lt;h1&gt;Hello, {props.user}!&lt;/h1&gt;</blockquote>",
        "It is standard to call this value <code>props</code> and when dealing with stateless functional components, you basically consider it as an argument to a function which returns JSX. You can access the value of the argument in the function body. With class components, you will see this is a little different.",
        "<hr>",
        "There is a <code>Calendar</code> and <code>CurrentDate</code> component in the code editor. When rendering <code>CurrentDate</code> from the <code>Calendar</code> component, pass in a property of <code>date</code> assigned to the current date from JavaScript's <code>Date</code> object. Then access this <code>prop</code> in the <code>CurrentDate</code> component, showing its value within the <code>p</code> tags. Note that for <code>prop</code> values to be evaluated as JavaScript, they must be enclosed in curly brackets, for instance <code>date={Date()}</code>."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "",
            "const CurrentDate = (props) => {",
            "  return (",
            "    <div>",
            "      { /* change code below this line */ }",
            "      <p>The current date is: </p>",
            "      { /* change code above this line */ }",
            "    </div>",
            "  );",
            "};",
            "",
            "class Calendar extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "  }",
            "  render() {",
            "    return (",
            "      <div>",
            "        <h3>What date is it?</h3>",
            "        { /* change code below this line */ }",
            "        <CurrentDate />",
            "        { /* change code above this line */ }",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<Calendar />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); return mockedComponent.children().type() === 'div'; })(), 'message: The <code>Calendar</code> component should return a single <code>div</code> element.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); return mockedComponent.children().childAt(1).name() === 'CurrentDate'; })(), 'message: The second child of the <code>Calendar</code> component should be the <code>CurrentDate</code> component.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); return mockedComponent.children().childAt(1).props().date })(), 'message: The <code>CurrentDate</code> component should have a prop called <code>date</code>.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); const prop = mockedComponent.children().childAt(1).props().date; return( typeof prop === 'string' && prop.length > 0 ); })(), 'message: The <code>date</code> prop of the <code>CurrentDate</code> should contain a string of text.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); return mockedComponent.find('p').html().includes(Date().substr(3)); })(), 'message: The <code>CurrentDate</code> component should render the value from the <code>date</code> prop in the <code>p</code> tag.');"
      ],
      "solutions": [
        "\nconst CurrentDate = (props) => {\n  return (\n    <div>\n      { /* change code below this line */ }\n      <p>The current date is: {props.date}</p>\n      { /* change code above this line */ }\n    </div>\n  );\n};\n\nclass Calendar extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n  render() {\n    return (\n      <div>\n        <h3>What date is it?</h3>\n        { /* change code below this line */ }\n        <CurrentDate date={Date()} />\n        { /* change code above this line */ }\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d403616a",
      "title": "Pass an Array as Props",
      "releasedOn": "December 25, 2017",
      "description": [
        "The last challenge demonstrated how to pass information from a parent component to a child component as <code>props</code> or properties. This challenge looks at how arrays can be passed as <code>props</code>.  To pass an array to a JSX element, it must be treated as JavaScript and wrapped in curly braces.",
        "<blockquote>&lt;ParentComponent&gt;<br>  &lt;ChildComponent colors={[\"green\", \"blue\", \"red\"]} /&gt;<br>&lt;/ParentComponent&gt;</blockquote>",
        "The child component then has access to the array property <code>colors</code>.  Array methods such as <code>join()</code> can be used when accessing the property.",
        "<code>const ChildComponent = (props) => &lt;p&gt{props.colors.join(', ')}&lt;/p&gt</code>",
        "This will join all <code>colors</code> array items into a comma separated string and produce:",
        " <code> &lt;p&gt;green, blue, red&lt;/p&gt;</code>",
        "Later, we will learn about other common methods to render arrays of data in React.",
        "<hr>",
        "There are <code>List</code> and <code>ToDo</code> components in the code editor. When rendering each <code>List</code> from the <code>ToDo</code> component, pass in a <code>tasks</code> property assigned to an array of to-do tasks, for example <code>[\"walk dog\", \"workout\"]</code>. Then access this <code>tasks</code> array in the <code>List</code> component, showing its value within the <code>p</code> element.  Use <code>join(\", \")</code> to display the <code>props.tasks</code>array in the <code>p</code> element as a comma separated list. Today's list should have at least 2 tasks and tomorrow's should have at least 3 tasks."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "const List= (props) => {",
            "  { /* change code below this line */ }",
            "  return <p>{}</p>",
            "  { /* change code above this line */ }",
            "};",
            "",
            "class ToDo extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "  }",
            "  render() {",
            "    return (",
            "      <div>",
            "        <h1>To Do Lists</h1>",
            "        <h2>Today</h2>",
            "        { /* change code below this line */ }",
            "        <List/>",
            "        <h2>Tomorrow</h2>",
            "        <List/>",
            "        { /* change code above this line */ }",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<ToDo />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.children().first().type() === 'div'; })(), 'message: The <code>ToDo</code> component should return a single outer <code>div</code>.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.children().first().childAt(2).name() === 'List'; })(), 'message: The third child of the <code>ToDo</code> component should be an instance of the <code>List</code> component.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.children().first().childAt(4).name() === 'List'; })(), 'message: The fifth child of the <code>ToDo</code> component should be an instance of the <code>List</code> component.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return Array.isArray(mockedComponent.find('List').get(0).props.tasks) && Array.isArray(mockedComponent.find('List').get(1).props.tasks); })(), 'message: Both instances of the <code>List</code> component should have a property called <code>tasks</code> and <code>tasks</code> should be of type array.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.find('List').get(0).props.tasks.length >= 2; })(), 'message: The first <code>List</code> component representing the tasks for today should have 2 or more items.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.find('List').get(1).props.tasks.length >= 3; })(), 'message: The second <code>List</code> component representing the tasks for tomorrow should have 3 or more items.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.find('p').get(0).props.children === mockedComponent.find('List').get(0).props.tasks.join(', ') && mockedComponent.find('p').get(1).props.children === mockedComponent.find('List').get(1).props.tasks.join(', '); })(), 'message: The <code>List</code> component should render the value from the <code>tasks</code> prop in the <code>p</code> tag.');"
      ],
      "solutions": [
        "const List= (props) => {\n  return <p>{props.tasks.join(', ')}</p>\n};\n\nclass ToDo extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n  render() {\n    return (\n      <div>\n        <h1>To Do Lists</h1>\n        <h2>Today</h2>\n        <List tasks={['study', 'exercise']} />\n        <h2>Tomorrow</h2>\n        <List tasks={['call Sam', 'grocery shopping', 'order tickets']} />\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d403616b",
      "title": "Use Default Props",
      "releasedOn": "December 25, 2017",
      "description": [
        "React also has an option to set default props. You can assign default props to a component as a property on the component itself and React assigns the default prop if necessary. This allows you to specify what a prop value should be if no value is explicitly provided. For example, if you declare <code>MyComponent.defaultProps = { location: 'San Francisco' }</code>, you have defined a location prop that's set to the string <code>San Francisco</code>, unless you specify otherwise. React assigns default props if props are undefined, but if you pass <code>null</code> as the value for a prop, it will remain <code>null</code>.",
        "<hr>",
        "The code editor shows a <code>ShoppingCart</code> component. Define default props on this component which specify a prop <code>items</code> with a value of <code>0</code>."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "const ShoppingCart = (props) => {",
            "  return (",
            "    <div>",
            "      <h1>Shopping Cart Component</h1>",
            "    </div>",
            "  )",
            "};",
            "// change code below this line",
            ""
          ],
          "tail": "ReactDOM.render(<ShoppingCart />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); return mockedComponent.find('ShoppingCart').length === 1; })(), 'message: The <code>ShoppingCart</code> component should render.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); mockedComponent.setProps({items: undefined}); return mockedComponent.find('ShoppingCart').props().items === 0; })(), 'message: The <code>ShoppingCart</code> component should have a default prop of <code>{ items: 0 }</code>.');"
      ],
      "solutions": [
        "const ShoppingCart = (props) => {\n  return (\n    <div>\n      <h1>Shopping Cart Component</h1>\n    </div>\n  )\n};\n\n// change code below this line\nShoppingCart.defaultProps = {\n  items: 0\n}"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d403616c",
      "title": "Override Default Props",
      "releasedOn": "December 25, 2017",
      "description": [
        "The ability to set default props is a useful feature in React. The way to override the default props is to explicitly set the prop values for a component.",
        "<hr>",
        "The <code>ShoppingCart</code> component now renders a child component <code>Items</code>. This <code>Items</code> component has a default prop <code>quantity</code> set to the integer <code>0</code>. Override the default prop by passing in a value of <code>10</code> for <code>quantity</code>.",
        "<strong>Note:</strong>&nbsp;Remember that the syntax to add a prop to a component looks similar to how you add HTML attributes. However, since the value for <code>quantity</code> is an integer, it won't go in quotes but it should be wrapped in curly braces. For example, <code>{100}</code>. This syntax tells JSX to interpret the value within the braces directly as JavaScript."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "const Items = (props) => {",
            "  return <h1>Current Quantity of Items in Cart: {props.quantity}</h1>",
            "}",
            "",
            "Items.defaultProps = {",
            "  quantity: 0",
            "}",
            "",
            "class ShoppingCart extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "  }",
            "  render() {",
            "    { /* change code below this line */ }",
            "    return <Items />",
            "    { /* change code above this line */ }",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<ShoppingCart />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); return mockedComponent.find('ShoppingCart').length === 1; })(), 'message: The component <code>ShoppingCart</code> should render.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); return mockedComponent.find('Items').length === 1; })(), 'message: The component <code>Items</code> should render.');",
        "getUserInput => assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); return mockedComponent.find('Items').props().quantity == 10 && getUserInput('index').replace(/ /g,'').includes('<Itemsquantity={10}/>'); })(), 'message: The <code>Items</code> component should have a prop of <code>{ quantity: 10 }</code> passed from the <code>ShoppingCart</code> component.');"
      ],
      "solutions": [
        "const Items = (props) => {\n  return <h1>Current Quantity of Items in Cart: {props.quantity}</h1>\n}\n\nItems.defaultProps = {\n  quantity: 0\n}\n\nclass ShoppingCart extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n  render() {\n    { /* change code below this line */ }\n    return <Items quantity = {10} />\n    { /* change code above this line */ }\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d403616d",
      "title": "Use PropTypes to Define the Props You Expect",
      "releasedOn": "December 25, 2017",
      "description": [
        "React provides useful type-checking features to verify that components receive props of the correct type. For example, your application makes an API call to retrieve data that you expect to be in an array, which is then passed to a component as a prop. You can set <code>propTypes</code> on your component to require the data to be of type <code>array</code>. This will throw a useful warning when the data is of any other type.",
        "It's considered a best practice to set <code>propTypes</code> when you know the type of a prop ahead of time. You can define a <code>propTypes</code> property for a component in the same way you defined <code>defaultProps</code>. Doing this will check that props of a given key are present with a given type. Here's an example to require the type <code>function</code> for a prop called <code>handleClick</code>:",
        "<code>MyComponent.propTypes = { handleClick: PropTypes.func.isRequired }</code>",
        "In the example above, the <code>PropTypes.func</code> part checks that <code>handleClick</code> is a function. Adding <code>isRequired</code> tells React that <code>handleClick</code> is a required property for that component. You will see a warning if that prop isn't provided. Also notice that <code>func</code> represents <code>function</code>. Among the seven JavaScript primitive types, <code>function</code> and <code>boolean</code> (written as <code>bool</code>) are the only two that use unusual spelling. In addition to the primitive types, there are other types available. For example, you can check that a prop is a React element. Please refer to the documentation for all of the options.",
        "<strong>Note:</strong> As of React v15.5.0, <code>PropTypes</code> is imported independently from React, like this:",
        "<code>import React, { PropTypes } from 'react';</code>",
        "<hr>",
        "Define <code>propTypes</code> for the <code>Items</code> component to require <code>quantity</code> as a prop and verify that it is of type <code>number</code>."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "head": [
            "var PropTypes = {",
            "  number: { isRequired: true }",
            "};",
            ""
          ],
          "contents": [
            "const Items = (props) => {",
            "  return <h1>Current Quantity of Items in Cart: {props.quantity}</h1>",
            "};",
            "",
            "// change code below this line",
            "",
            "// change code above this line",
            "",
            "Items.defaultProps = {",
            "  quantity: 0",
            "};",
            "",
            "class ShoppingCart extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "  }",
            "  render() {",
            "    return <Items />",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<ShoppingCart />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); return mockedComponent.find('ShoppingCart').length === 1; })(), 'message: The <code>ShoppingCart</code> component should render.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); return mockedComponent.find('Items').length === 1; })(), 'message: The <code>Items</code> component should render.');",
        "getUserInput => assert((function() { const noWhiteSpace = getUserInput('index').replace(/ /g, ''); return noWhiteSpace.includes('quantity:PropTypes.number.isRequired') && noWhiteSpace.includes('Items.propTypes='); })(), 'message: The <code>Items</code> component should include a <code>propTypes</code> check that requires <code>quantity</code> to be a <code>number</code>.');"
      ],
      "solutions": [
        "const Items = (props) => {\n  return <h1>Current Quantity of Items in Cart: {props.quantity}</h1>\n};\n\n// change code below this line\nItems.propTypes = {\n  quantity: PropTypes.number.isRequired\n};\n// change code above this line\n\nItems.defaultProps = {\n  quantity: 0\n};\n\nclass ShoppingCart extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n  render() {\n    return <Items />\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d403616e",
      "title": "Access Props Using this.props",
      "releasedOn": "December 25, 2017",
      "description": [
        "The last several challenges covered the basic ways to pass props to child components. But what if the child component that you're passing a prop to is an ES6 class component, rather than a stateless functional component? The ES6 class component uses a slightly different convention to access props.",
        "Anytime you refer to a class component within itself, you use the <code>this</code> keyword. To access props within a class component, you preface the code that you use to access it with <code>this</code>. For example, if an ES6 class component has a prop called <code>data</code>, you write <code>{this.props.data}</code> in JSX.",
        "<hr>",
        "Render an instance of the <code>ReturnTempPassword</code> component in the parent component <code>ResetPassword</code>. Here, give <code>ReturnTempPassword</code> a prop of <code>tempPassword</code> and assign it a value of a string that is at least 8 characters long. Within the child, <code>ReturnTempPassword</code>, access the <code>tempPassword</code> prop within the <code>strong</code> tags to make sure the user sees the temporary password."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class ReturnTempPassword extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "",
            "  }",
            "  render() {",
            "    return (",
            "        <div>",
            "            { /* change code below this line */ }",
            "            <p>Your temporary password is: <strong></strong></p>",
            "            { /* change code above this line */ }",
            "        </div>",
            "    );",
            "  }",
            "};",
            "",
            "class ResetPassword extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "",
            "  }",
            "  render() {",
            "    return (",
            "        <div>",
            "          <h2>Reset Password</h2>",
            "          <h3>We've generated a new temporary password for you.</h3>",
            "          <h3>Please reset this password from your account settings ASAP.</h3>",
            "          { /* change code below this line */ }",
            "",
            "          { /* change code above this line */ }",
            "        </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<ResetPassword />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); return mockedComponent.children().type() === 'div'; })(), 'message: The <code>ResetPassword</code> component should return a single <code>div</code> element.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); return mockedComponent.children().childAt(3).name() === 'ReturnTempPassword'; })(), 'message: The fourth child of <code>ResetPassword</code> should be the <code>ReturnTempPassword</code> component.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); return mockedComponent.find('ReturnTempPassword').props().tempPassword; })(), 'message: The <code>ReturnTempPassword</code> component should have a prop called <code>tempPassword</code>.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); const temp = mockedComponent.find('ReturnTempPassword').props().tempPassword; return typeof temp === 'string' && temp.length >= 8; })(), 'message: The <code>tempPassword</code> prop of <code>ReturnTempPassword</code> should be equal to a string of at least <code>8</code> characters.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); return mockedComponent.find('strong').text() && mockedComponent.find('ReturnTempPassword').props().tempPassword; })(), 'message: The <code>ReturnTempPassword</code> component should display the password you create as the <code>tempPassword</code> prop within <code>strong</code> tags.');"
      ],
      "solutions": [
        "class ReturnTempPassword extends React.Component {\n  constructor(props) {\n    super(props);\n\n  }\n  render() {\n    return (\n        <div>\n            <p>Your temporary password is: <strong>{this.props.tempPassword}</strong></p>\n        </div>\n    );\n  }\n};\n\nclass ResetPassword extends React.Component {\n  constructor(props) {\n    super(props);\n\n  }\n  render() {\n    return (\n        <div>\n          <h2>Reset Password</h2>\n          <h3>We've generated a new temporary password for you.</h3>\n          <h3>Please reset this password from your account settings ASAP.</h3>\n          { /* change code below this line */ }\n          <ReturnTempPassword tempPassword=\"serrPbqrPnzc\" />\n          { /* change code above this line */ }\n        </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d403616f",
      "title": "Review Using Props with Stateless Functional Components",
      "releasedOn": "December 25, 2017",
      "description": [
        "Except for the last challenge, you've been passing props to stateless functional components. These components act like pure functions. They accept props as input and return the same view every time they are passed the same props. You may be wondering what state is, and the next challenge will cover it in more detail. Before that, here's a review of the terminology for components.",
        "A <em>stateless functional component</em> is any function you write which accepts props and returns JSX. A <em>stateless component</em>, on the other hand, is a class that extends <code>React.Component</code>, but does not use internal state (covered in the next challenge). Finally, a <em>stateful component</em> is any component that does maintain its own internal state. You may see stateful components referred to simply as components or React components.",
        "A common pattern is to try to minimize statefulness and to create stateless functional components wherever possible. This helps contain your state management to a specific area of your application. In turn, this improves development and maintenance of your app by making it easier to follow how changes to state affect its behavior.",
        "<hr>",
        "The code editor has a <code>CampSite</code> component that renders a <code>Camper</code> component as a child. Define the <code>Camper</code> component and assign it default props of <code>{ name: 'CamperBot' }</code>. Inside the <code>Camper</code> component, render any code that you want, but make sure to have one <code>p</code> element that includes only the <code>name</code> value that is passed in as a <code>prop</code>. Finally, define <code>propTypes</code> on the <code>Camper</code> component to require <code>name</code> to be provided as a prop and verify that it is of type <code>string</code>."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "head": [
            "var PropTypes = {",
              "   string: { isRequired: true }",
              "};"
          ],
          "contents": [
            "class CampSite extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "  }",
            "  render() {",
            "    return (",
            "      <div>",
            "        <Camper/>",
            "      </div>",
            "    );",
            "  }",
            "};",
            "// change code below this line",
            ""
          ],
          "tail": "ReactDOM.render(<CampSite />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(CampSite)); return mockedComponent.find('CampSite').length === 1; })(), 'message: The <code>CampSite</code> component should render.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(CampSite)); return mockedComponent.find('Camper').length === 1; })(), 'message: The <code>Camper</code> component should render.');",
        "getUserInput => assert((function() { const noWhiteSpace = getUserInput('index').replace(/\\s/g, ''); const verify1 = 'Camper.defaultProps={name:\\'CamperBot\\'}'; const verify2 = 'Camper.defaultProps={name:\"CamperBot\"}'; return (noWhiteSpace.includes(verify1) || noWhiteSpace.includes(verify2)); })(), 'message: The <code>Camper</code> component should include default props which assign the string <code>CamperBot</code> to the key <code>name</code>.');",
        "getUserInput => assert((function() { const mockedComponent = Enzyme.mount(React.createElement(CampSite)); const noWhiteSpace = getUserInput('index').replace(/\\s/g, ''); const verifyDefaultProps = 'Camper.propTypes={name:PropTypes.string.isRequired}'; return noWhiteSpace.includes(verifyDefaultProps); })(), 'message: The <code>Camper</code> component should include prop types which require the <code>name</code> prop to be of type <code>string</code>.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(CampSite)); return mockedComponent.find('p').text() === mockedComponent.find('Camper').props().name; })(), 'message: The <code>Camper</code> component should contain a <code>p</code> element with only the text from the <code>name</code> prop.');"
      ],
      "solutions": [
        "class CampSite extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n  render() {\n    return (\n      <div>\n        <Camper/>\n      </div>\n    );\n  }\n};\n// change code below this line\n\nconst Camper = (props) => {\n   return (\n     <div>\n       <p>{props.name}</p>\n     </div>\n   );\n};\n\nCamper.propTypes = {\n  name: PropTypes.string.isRequired\n};\n\nCamper.defaultProps = {\n  name: 'CamperBot'\n};\n"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036170",
      "title": "Create a Stateful Component",
      "releasedOn": "December 25, 2017",
      "description": [
        "One of the most important topics in React is <code>state</code>. State consists of any data your application needs to know about, that can change over time. You want your apps to respond to state changes and present an updated UI when necessary. React offers a nice solution for the state management of modern web applications.",
        "You create state in a React component by declaring a <code>state</code> property on the component class in its <code>constructor</code>. This initializes the component with <code>state</code> when it is created. The <code>state</code> property must be set to a JavaScript <code>object</code>. Declaring it looks like this:",
        "<blockquote>this.state = {<br>  // describe your state here<br>}</code>",
        "You have access to the <code>state</code> object throughout the life of your component. You can update it, render it in your UI, and pass it as props to child components. The <code>state</code> object can be as complex or as simple as you need it to be. Note that you must create a class component by extending <code>React.Component</code> in order to create <code>state</code> like this.",
        "<hr>",
        "There is a component in the code editor that is trying to render a <code>name</code> property from its <code>state</code>. However, there is no <code>state</code> defined. Initialize the component with <code>state</code> in the <code>constructor</code> and assign your name to a property of <code>name</code>."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "",
            "class StatefulComponent extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    // initialize state here",
            "",
            "  }",
            "  render() {",
            "    return (",
            "      <div>",
            "        <h1>{this.state.name}</h1>",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<StatefulComponent />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); return mockedComponent.find('StatefulComponent').length === 1; })(), 'message: <code>StatefulComponent</code> should exist and render.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); return mockedComponent.find('div').length === 1 && mockedComponent.find('h1').length === 1; })(), 'message: <code>StatefulComponent</code> should render a <code>div</code> and an <code>h1</code> element.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); const initialState = mockedComponent.state(); return ( typeof initialState === 'object' && typeof initialState.name === 'string'); })(), 'message: The state of <code>StatefulComponent</code> should be initalized with a property <code>name</code> set to a string.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); const initialState = mockedComponent.state(); return mockedComponent.find('h1').text() === initialState.name; })(), 'message: The property <code>name</code> in the state of <code>StatefulComponent</code> should render in the <code>h1</code> element.');"
      ],
      "solutions": [
        "\nclass StatefulComponent extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      name: 'freeCodeCamp!'\n    }\n  }\n  render() {\n    return (\n      <div>\n        <h1>{this.state.name}</h1>\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036171",
      "title": "Render State in the User Interface",
      "releasedOn": "December 25, 2017",
      "description": [
        "Once you define a component's initial state, you can display any part of it in the UI that is rendered. If a component is stateful, it will always have access to the data in <code>state</code> in its <code>render()</code> method. You can access the data with <code>this.state</code>.",
        "If you want to access a state value within the <code>return</code> of the render method, you have to enclose the value in curly braces.",
        "<code>State</code> is one of the most powerful features of components in React. It allows you to track important data in your app and render a UI in response to changes in this data. If your data changes, your UI will change. React uses what is called a virtual DOM, to keep track of changes behind the scenes. When state data updates, it triggers a re-render of the components using that data - including child components that received the data as a prop. React updates the actual DOM, but only where necessary. This means you don't have to worry about changing the DOM. You simply declare what the UI should look like.",
        "Note that if you make a component stateful, no other components are aware of its <code>state</code>. Its <code>state</code> is completely encapsulated, or local to that component, unless you pass state data to a child component as <code>props</code>. This notion of encapsulated <code>state</code> is very important because it allows you to write certain logic, then have that logic contained and isolated in one place in your code.",
        "<hr>",
        "In the code editor, <code>MyComponent</code> is already stateful. Define an <code>h1</code> tag in the component's render method which renders the value of <code>name</code> from the component's state.",
        "<strong>Note:</strong>&nbsp;The <code>h1</code> should only render the value from <code>state</code> and nothing else. In JSX, any code you write with curly braces <code>{ }</code> will be treated as JavaScript. So to access the value from <code>state</code> just enclose the reference in curly braces."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class MyComponent extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      name: 'freeCodeCamp'",
            "    }",
            "  }",
            "  render() {",
            "    return (",
            "      <div>",
            "        { /* change code below this line */ }",
            "",
            "        { /* change code above this line */ }",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<MyComponent />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert(Enzyme.mount(React.createElement(MyComponent)).state('name') === 'freeCodeCamp', 'message: <code>MyComponent</code> should have a key <code>name</code> with value <code>freeCodeCamp</code> stored in its state.');",
        "assert(/<div><h1>.*<\\/h1><\\/div>/.test(Enzyme.mount(React.createElement(MyComponent)).html()), 'message: <code>MyComponent</code> should render an <code>h1</code> header enclosed in a single <code>div</code>.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ name: 'TestName' });   return waitForIt(() => mockedComponent.html()) }; const firstValue = await first(); assert(firstValue === '<div><h1>TestName</h1></div>', 'message: The rendered <code>h1</code> header should contain text rendered from the component&apos;s state.');};"
      ],
      "solutions": [
        "class MyComponent extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      name: 'freeCodeCamp'\n    }\n  }\n  render() {\n    return (\n      <div>\n        { /* change code below this line */ }\n        <h1>{this.state.name}</h1>\n        { /* change code above this line */ }\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036172",
      "title": "Render State in the User Interface Another Way",
      "releasedOn": "December 25, 2017",
      "description": [
        "There is another way to access <code>state</code> in a component. In the <code>render()</code> method, before the <code>return</code> statement, you can write JavaScript directly. For example, you could declare functions, access data from <code>state</code> or <code>props</code>, perform computations on this data, and so on. Then, you can assign any data to variables, which you have access to in the <code>return</code> statement.",
        "<hr>",
        "In the <code>MyComponent</code> render method, define a <code>const</code> called <code>name</code> and set it equal to the name value in the component's <code>state</code>. Because you can write JavaScript directly in this part of the code, you don't have to enclose this reference in curly braces.",
        "Next, in the return statement, render this value in an <code>h1</code> tag using the variable <code>name</code>. Remember, you need to use the JSX syntax (curly braces for JavaScript) in the return statement."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class MyComponent extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      name: 'freeCodeCamp'",
            "    }",
            "  }",
            "  render() {",
            "    // change code below this line",
            "",
            "    // change code above this line",
            "    return (",
            "      <div>",
            "        { /* change code below this line */ }",
            "",
            "        { /* change code above this line */ }",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<MyComponent />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert(Enzyme.mount(React.createElement(MyComponent)).state('name') === 'freeCodeCamp', 'message: <code>MyComponent</code> should have a key <code>name</code> with value <code>freeCodeCamp</code> stored in its state.');",
        "assert(/<div><h1>.*<\\/h1><\\/div>/.test(Enzyme.mount(React.createElement(MyComponent)).html()), 'message: <code>MyComponent</code> should render an <code>h1</code> header enclosed in a single <code>div</code>.');",
        "getUserInput => assert(/<h1>\\n*\\s*\\{\\s*name\\s*\\}\\s*\\n*<\\/h1>/.test(getUserInput('index')), 'message: The rendered <code>h1</code> tag should include a reference to <code>{name}</code>.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ name: 'TestName' });   return waitForIt(() => mockedComponent.html()) }; const firstValue = await first(); assert(firstValue === '<div><h1>TestName</h1></div>', 'message: The rendered <code>h1</code> header should contain text rendered from the component&apos;s state.'); };"
      ],
      "solutions": [
        "class MyComponent extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      name: 'freeCodeCamp'\n    }\n  }\n  render() {\n    // change code below this line\n    const name = this.state.name;\n    // change code above this line\n    return (\n      <div>\n        { /* change code below this line */ }\n        <h1>{name}</h1>\n        { /* change code above this line */ }\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036173",
      "title": "Set State with this.setState",
      "releasedOn": "December 25, 2017",
      "description": [
        "The previous challenges covered component <code>state</code> and how to initialize state in the <code>constructor</code>. There is also a way to change the component's <code>state</code>. React provides a method for updating component <code>state</code> called <code>setState</code>. You call the <code>setState</code> method within your component class like so: <code>this.setState()</code>, passing in an object with key-value pairs. The keys are your state properties and the values are the updated state data. For instance, if we were storing a <code>username</code> in state and wanted to update it, it would look like this:",
        "<blockquote>this.setState({<br> username: 'Lewis'<br>});</blockquote>",
        "React expects you to never modify <code>state</code> directly, instead always use <code>this.setState()</code> when state changes occur. Also, you should note that React may batch multiple state updates in order to improve performance. What this means is that state updates through the <code>setState</code> method can be asynchronous. There is an alternative syntax for the <code>setState</code> method which provides a way around this problem. This is rarely needed but it's good to keep it in mind! Please consult the <a target=\"_blank\" href=\"https://facebook.github.io/react/docs/state-and-lifecycle.html\">React documentation</a> for further details.",
        "<hr>",
        "There is a <code>button</code> element in the code editor which has an <code>onClick()</code> handler. This handler is triggered when the <code>button</code> receives a click event in the browser, and runs the <code>handleClick</code> method defined on <code>MyComponent</code>. Within the <code>handleClick</code> method, update the component <code>state</code> using <code>this.setState()</code>. Set the <code>name</code> property in <code>state</code> to equal the string <code>React Rocks!</code>.",
        "Click the button and watch the rendered state update. Don't worry if you don't fully understand how the click handler code works at this point. It's covered in upcoming challenges."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class MyComponent extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      name: 'Initial State'",
            "    };",
            "    this.handleClick = this.handleClick.bind(this);",
            "  }",
            "  handleClick() {",
            "    // change code below this line",
            "",
            "    // change code above this line",
            "  }",
            "  render() {",
            "    return (",
            "      <div>",
            "        <button onClick={this.handleClick}>Click Me</button>",
            "        <h1>{this.state.name}</h1>",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<MyComponent />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert(Enzyme.mount(React.createElement(MyComponent)).state('name') === 'Initial State', 'message: The state of <code>MyComponent</code> should initialize with the key value pair <code>{ name: Initial State }</code>.');",
        "assert(Enzyme.mount(React.createElement(MyComponent)).find('h1').length === 1, 'message: <code>MyComponent</code> should render an <code>h1</code> header.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ name: 'TestName' }); return waitForIt(() => mockedComponent.html()); }; const firstValue = await first(); assert(/<h1>TestName<\\/h1>/.test(firstValue), 'message: The rendered <code>h1</code> header should contain text rendered from the component&apos;s state.'); };",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ name: 'Before' }); return waitForIt(() => mockedComponent.state('name')); }; const second = () => { mockedComponent.instance().handleClick(); return waitForIt(() => mockedComponent.state('name')); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === 'Before' && secondValue === 'React Rocks!', 'message: Calling the <code>handleClick</code> method on <code>MyComponent</code> should set the name property in state to equal <code>React Rocks!</code>.'); };"
      ],
      "solutions": [
        "class MyComponent extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      name: 'Initial State'\n    };\n    this.handleClick = this.handleClick.bind(this);\n  }\n  handleClick() {\n     // change code below this line\n    this.setState({\n      name: 'React Rocks!'\n    });\n    // change code above this line\n  }\n  render() {\n    return (\n      <div>\n        <button onClick = {this.handleClick}>Click Me</button>\n        <h1>{this.state.name}</h1>\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036174",
      "title": "Bind 'this' to a Class Method",
      "releasedOn": "December 25, 2017",
      "description": [
        "In addition to setting and updating <code>state</code>, you can also define methods for your component class. A class method typically needs to use the <code>this</code> keyword so it can access properties on the class (such as <code>state</code> and <code>props</code>) inside the scope of the method. There are a few ways to allow your class methods to access <code>this</code>.",
        "One common way is to explicitly bind <code>this</code> in the constructor so <code>this</code> becomes bound to the class methods when the component is initialized. You may have noticed the last challenge used <code>this.handleClick = this.handleClick.bind(this)</code> for its <code>handleClick</code> method in the constructor. Then, when you call a function like <code>this.setState()</code> within your class method, <code>this</code> refers to the class and will not be <code>undefined</code>.",
        "<strong>Note:</strong>&nbsp;The <code>this</code> keyword is one of the most confusing aspects of JavaScript but it plays an important role in React. Although its behavior here is totally normal, these lessons aren't the place for an in-depth review of <code>this</code> so please refer to other lessons if the above is confusing!",
        "<hr>",
        "The code editor has a component with a <code>state</code> that keeps track of an item count. It also has a method which allows you to increment this item count. However, the method doesn't work because it's using the <code>this</code> keyword that is undefined. Fix it by explicitly binding <code>this</code> to the <code>addItem()</code> method in the component's constructor.",
        "Next, add a click handler to the <code>button</code> element in the render method. It should trigger the <code>addItem()</code> method when the button receives a click event. Remember that the method you pass to the <code>onClick</code> handler needs curly braces because it should be interpreted directly as JavaScript.",
        "Once you complete the above steps you should be able to click the button and see the item count increment in the HTML."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class MyComponent extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      itemCount: 0",
            "    };",
            "    // change code below this line",
            "",
            "    // change code above this line",
            "  }",
            "  addItem() {",
            "    this.setState({",
            "      itemCount: this.state.itemCount + 1",
            "    });",
            "  }",
            "  render() {",
            "    return (",
            "      <div>",
            "        { /* change code below this line */ }",
            "        <button>Click Me</button>",
            "        { /* change code above this line */ }",
            "        <h1>Current Item Count: {this.state.itemCount}</h1>",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<MyComponent />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert(Enzyme.mount(React.createElement(MyComponent)).find('div').length === 1 && Enzyme.mount(React.createElement(MyComponent)).find('div').childAt(0).type() === 'button' && Enzyme.mount(React.createElement(MyComponent)).find('div').childAt(1).type() === 'h1', 'message: <code>MyComponent</code> should return a <code>div</code> element which wraps two elements, a button and an <code>h1</code> element, in that order.');",
        "assert(Enzyme.mount(React.createElement(MyComponent)).state('itemCount') === 0, 'message: The state of <code>MyComponent</code> should initialize with the key value pair <code>{ itemCount: 0 }</code>.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ itemCount: 0 }); return waitForIt(() => mockedComponent.state('itemCount')); }; const second = () => { mockedComponent.find('button').simulate('click'); return waitForIt(() => mockedComponent.state('itemCount')); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === 0 && secondValue === 1, 'message: Clicking the <code>button</code> element should run the <code>addItem</code> method and increment the state <code>itemCount</code> by <code>1</code>.'); };"
      ],
      "solutions": [
        "class MyComponent extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      itemCount: 0\n    };\n    this.addItem = this.addItem.bind(this);\n  }\n  addItem() {\n    this.setState({\n      itemCount: this.state.itemCount + 1\n    });\n  }\n  render() {\n    return (\n      <div>\n        <button onClick = {this.addItem}>Click Me</button>\n        <h1>Current Item Count: {this.state.itemCount}</h1>\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036176",
      "title": "Use State to Toggle an Element",
      "releasedOn": "December 25, 2017",
      "description": [
        "You can use <code>state</code> in React applications in more complex ways than what you've seen so far. One example is to monitor the status of a value, then render the UI conditionally based on this value. There are several different ways to accomplish this, and the code editor shows one method.",
        "<hr>",
        "<code>MyComponent</code> has a <code>visibility</code> property which is initialized to <code>false</code>. The render method returns one view if the value of <code>visibility</code> is true, and a different view if it is false.",
        "Currently, there is no way of updating the <code>visibility</code> property in the component's <code>state</code>. The value should toggle back and forth between true and false. There is a click handler on the button which triggers a class method called <code>toggleVisibility()</code>. Define this method so the <code>state</code> of <code>visibility</code> toggles to the opposite value when the method is called. If <code>visibility</code> is <code>false</code>, the method sets it to <code>true</code>, and vice versa.",
        "Finally, click the button to see the conditional rendering of the component based on its <code>state</code>.",
        "<strong>Hint:</strong>&nbsp;Don't forget to bind the <code>this</code> keyword to the method in the constructor!"
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class MyComponent extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      visibility: false",
            "    };",
            "    // change code below this line",
            "",
            "    // change code above this line",
            "  }",
            "  // change code below this line",
            "",
            "  // change code above this line",
            "  render() {",
            "    if (this.state.visibility) {",
            "      return (",
            "        <div>",
            "          <button onClick={this.toggleVisibility}>Click Me</button>",
            "          <h1>Now you see me!</h1>",
            "        </div>",
            "      );",
            "    } else {",
            "      return (",
            "        <div>",
            "          <button onClick={this.toggleVisibility}>Click Me</button>",
            "        </div>",
            "      );",
            "    }",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<MyComponent />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert.strictEqual(Enzyme.mount(React.createElement(MyComponent)).find('div').find('button').length, 1, 'message: <code>MyComponent</code> should return a <code>div</code> element which contains a <code>button</code>.');",
        "assert.strictEqual(Enzyme.mount(React.createElement(MyComponent)).state('visibility'), false, 'message: The state of <code>MyComponent</code> should initialize with a <code>visibility</code> property set to <code>false</code>.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ visibility: false }); return waitForIt(() => mockedComponent.state('visibility')); }; const second = () => { mockedComponent.find('button').simulate('click'); return waitForIt(() => mockedComponent.state('visibility')); }; const third = () => { mockedComponent.find('button').simulate('click'); return waitForIt(() => mockedComponent.state('visibility')); }; const firstValue = await first(); const secondValue = await second(); const thirdValue = await third(); assert(!firstValue && secondValue && !thirdValue, 'message: Clicking the button element should toggle the <code>visibility</code> property in state between <code>true</code> and <code>false</code>.'); }; "
      ],
      "solutions": [
        "class MyComponent extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      visibility: false\n    };\n    this.toggleVisibility = this.toggleVisibility.bind(this);\n   }\n  toggleVisibility() {\n    this.setState({\n      visibility: !this.state.visibility\n    });\n  }\n  render() {\n    if (this.state.visibility) {\n      return (\n        <div>\n          <button onClick = {this.toggleVisibility}>Click Me</button>\n          <h1>Now you see me!</h1>\n        </div>\n      );\n    } else {\n      return (\n        <div>\n          <button onClick = {this.toggleVisibility}>Click Me</button>\n        </div>\n      );\n    }\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036177",
      "title": "Write a Simple Counter",
      "releasedOn": "December 25, 2017",
      "description": [
        "You can design a more complex stateful component by combining the concepts covered so far. These include initializing <code>state</code>, writing methods that set <code>state</code>, and assigning click handlers to trigger these methods.",
        "<hr>",
        "The <code>Counter</code> component keeps track of a <code>count</code> value in <code>state</code>. There are two buttons which call methods <code>increment()</code> and <code>decrement()</code>. Write these methods so the counter value is incremented or decremented by 1 when the appropriate button is clicked. Also, create a <code>reset()</code> method so when the reset button is clicked, the count is set to 0.",
        "<strong>Note:</strong>&nbsp;Make sure you don't modify the <code>classNames</code> of the buttons. Also, remember to add the necessary bindings for the newly-created methods in the constructor."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class Counter extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      count: 0",
            "    };",
            "    // change code below this line",
            "",
            "    // change code above this line",
            "  }",
            "  // change code below this line",
            "",
            "  // change code above this line",
            "  render() {",
            "    return (",
            "      <div>",
            "        <button className='inc' onClick={this.increment}>Increment!</button>",
            "        <button className='dec' onClick={this.decrement}>Decrement!</button>",
            "        <button className='reset' onClick={this.reset}>Reset</button>",
            "        <h1>Current Count: {this.state.count}</h1>",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<Counter />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((() => { const mockedComponent = Enzyme.mount(React.createElement(Counter)); return (mockedComponent.find('.inc').text() === 'Increment!' && mockedComponent.find('.dec').text() === 'Decrement!' && mockedComponent.find('.reset').text() === 'Reset'); })(), 'message: <code>MyComponent</code> should return a <code>div</code> element which contains three buttons with text content in this order <code>Increment!</code>, <code>Decrement!</code>, <code>Reset</code>.');",
        "assert.strictEqual(Enzyme.mount(React.createElement(Counter)).state('count'), 0, 'message: The state of <code>MyComponent</code> should initialize with a <code>count</code> property set to <code>0</code>.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(Counter)); const first = () => { mockedComponent.setState({ count: 0 }); return waitForIt(() => mockedComponent.state('count')); }; const second = () => { mockedComponent.find('.inc').simulate('click'); return waitForIt(() => mockedComponent.state('count')); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === 0 && secondValue === 1, 'message: Clicking the increment button should increment the count by <code>1</code>.'); }; ",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(Counter)); const first = () => { mockedComponent.setState({ count: 0 }); return waitForIt(() => mockedComponent.state('count')); }; const second = () => { mockedComponent.find('.dec').simulate('click'); return waitForIt(() => mockedComponent.state('count')); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === 0 && secondValue === -1, 'message: Clicking the decrement button should decrement the count by <code>1</code>.'); }; ",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(Counter)); const init = () => { mockedComponent.setState({ count: 0 }); return waitForIt(() => mockedComponent.state('count')); }; const increment = () => { mockedComponent.find('.inc').simulate('click'); mockedComponent.find('.inc').simulate('click'); return waitForIt(() => mockedComponent.state('count')); }; const decrement = () => { mockedComponent.find('.dec').simulate('click'); return waitForIt(() => mockedComponent.state('count')); }; const reset = () => { mockedComponent.find('.reset').simulate('click'); return waitForIt(() => mockedComponent.state('count')); }; const firstValue = await init(); const secondValue = await increment(); const thirdValue = await decrement(); const fourthValue = await reset(); assert(firstValue === 0 && secondValue === 2 && thirdValue === 1 && fourthValue === 0, 'message: Clicking the reset button should reset the count to <code>0</code>.'); }; "
      ],
      "solutions": [
        "class Counter extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      count: 0\n    };\n  this.increment = this.increment.bind(this);\n this.decrement = this.decrement.bind(this);\n this.reset = this.reset.bind(this);\n }\n  reset() {\n    this.setState({\n      count: 0\n    });\n  }\n  increment() {\n    this.setState({\n      count: this.state.count + 1\n    });\n  }\n  decrement() {\n    this.setState({\n      count: this.state.count - 1\n    });\n  }\n  render() {\n    return (\n      <div>\n        <button className='inc' onClick={this.increment}>Increment!</button>\n        <button className='dec' onClick={this.decrement}>Decrement!</button>\n        <button className='reset' onClick={this.reset}>Reset</button>\n        <h1>Current Count: {this.state.count}</h1>\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036178",
      "title": "Create a Controlled Input",
      "releasedOn": "December 25, 2017",
      "description": [
        "Your application may have more complex interactions between <code>state</code> and the rendered UI. For example, form control elements for text input, such as <code>input</code> and <code>textarea</code>, maintain their own state in the DOM as the user types. With React, you can move this mutatable state into a React component's <code>state</code>. The user's input becomes part of the application <code>state</code>, so React controls the value of that input field. Typically, if you have React components with input fields the user can type into, it will be a controlled input form.",
        "<hr>",
        "The code editor has the skeleton of a component called <code>ControlledInput</code> to create a controlled <code>input</code> element. The component's <code>state</code> is already initialized with an <code>input</code> property that holds an empty string. This value represents the text a user types into the <code>input</code> field.",
        "First, create a method called <code>handleChange()</code> that has a parameter called <code>event</code>. When the method is called, it receives an <code>event</code> object that contains a string of text from the <code>input</code> element. You can access this string with <code>event.target.value</code> inside the method. Update the <code>input</code> property of the component's <code>state</code> with this new string.",
        "In the render method, create the <code>input</code> element above the <code>h4</code> tag. Add a <code>value</code> attribute which is equal to the <code>input</code> property of the component's <code>state</code>. Then add an <code>onChange()</code> event handler set to the <code>handleChange()</code> method.",
        "When you type in the input box, that text is processed by the <code>handleChange()</code> method, set as the <code>input</code> property in the local <code>state</code>, and rendered as the value in the <code>input</code> box on the page. The component <code>state</code> is the single source of truth regarding the input data.",
        "Last but not least, don't forget to add the necessary bindings in the constructor."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class ControlledInput extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      input: ''",
            "    };",
            "    // change code below this line",
            "",
            "    // change code above this line",
            "  }",
            "  // change code below this line",
            "",
            "  // change code above this line",
            "  render() {",
            "    return (",
            "      <div>",
            "        { /* change code below this line */}",
            "",
            "        { /* change code above this line */}",
            "        <h4>Controlled Input:</h4>",
            "        <p>{this.state.input}</p>",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<ControlledInput />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert(Enzyme.mount(React.createElement(ControlledInput)).find('div').children().find('input').length === 1 && Enzyme.mount(React.createElement(ControlledInput)).find('div').children().find('p').length === 1, 'message: <code>ControlledInput</code> should return a <code>div</code> element which contains an <code>input</code> and a <code>p</code> tag.');",
        "assert.strictEqual(Enzyme.mount(React.createElement(ControlledInput)).state('input'), '', 'message: The state of <code>ControlledInput</code> should initialize with an <code>input</code> property set to an empty string.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(ControlledInput)); const _1 = () => { mockedComponent.setState({ input: '' }); return waitForIt(() => mockedComponent.state('input'))}; const _2 = () => { mockedComponent.find('input').simulate('change', { target: { value: 'TestInput' }}); return waitForIt(() => ({ state: mockedComponent.state('input'), text: mockedComponent.find('p').text(), inputVal: mockedComponent.find('input').props().value }))}; const before = await _1(); const after = await _2(); assert(before === '' && after.state === 'TestInput' && after.text === 'TestInput' && after.inputVal === 'TestInput', 'message: Typing in the input element should update the state and the value of the input, and the <code>p</code> element should render this state as you type.'); }; "
      ],
      "solutions": [
        "class ControlledInput extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      input: ''\n    };\n    this.handleChange = this.handleChange.bind(this);\n  }\n  handleChange(event) {\n    this.setState({\n      input: event.target.value\n    });\n  }\n  render() {\n    return (\n      <div>\n        <input\n          value={this.state.input}\n          onChange={this.handleChange} />\n        <h4>Controlled Input:</h4>\n\n        <p>{this.state.input}</p>\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036179",
      "title": "Create a Controlled Form",
      "releasedOn": "December 25, 2017",
      "description": [
        "The last challenge showed that React can control the internal state for certain elements like <code>input</code> and <code>textarea</code>, which makes them controlled components. This applies to other form elements as well, including the regular HTML <code>form</code> element.",
        "<hr>",
        "The <code>MyForm</code> component is set up with an empty <code>form</code> with a submit handler. The submit handler will be called when the formed is submitted.",
        "We've added a button which submits the form. You can see it has the <code>type</code> set to <code>submit</code> indicating it is the button controlling the form. Add the <code>input</code> element in the <code>form</code> and set its <code>value</code> and <code>onChange()</code> attributes like the last challenge. You should then complete the <code>handleSubmit</code> method so that it sets the component state property <code>submit</code> to the current input value in the local <code>state</code>.",
        "<strong>Note:</strong>&nbsp; You also must call <code>event.preventDefault()</code> in the submit handler, to prevent the default form submit behavior which will refresh the web page.",
        "Finally, create an <code>h1</code> tag after the <code>form</code> which renders the <code>submit</code> value from the component's <code>state</code>. You can then type in the form and click the button (or press enter), and you should see your input rendered to the page."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class MyForm extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      input: '',",
            "      submit: ''",
            "    };",
            "    this.handleChange = this.handleChange.bind(this);",
            "    this.handleSubmit = this.handleSubmit.bind(this);",
            "  }",
            "  handleChange(event) {",
            "    this.setState({",
            "      input: event.target.value",
            "    });",
            "  }",
            "  handleSubmit(event) {",
            "    // change code below this line",
            "",
            "    // change code above this line",
            "  }",
            "  render() {",
            "    return (",
            "      <div>",
            "        <form onSubmit={this.handleSubmit}>",
            "          { /* change code below this line */ }",
            "",
            "          { /* change code above this line */ }",
            "          <button type='submit'>Submit!</button>",
            "        </form>",
            "        { /* change code below this line */ }",
            "",
            "        { /* change code above this line */ }",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<MyForm />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyForm)); return (mockedComponent.find('div').children().find('form').length === 1 && mockedComponent.find('div').children().find('h1').length === 1 && mockedComponent.find('form').children().find('input').length === 1 && mockedComponent.find('form').children().find('button').length === 1) })(), 'message: <code>MyForm</code> should return a <code>div</code> element which contains a <code>form</code> and an <code>h1</code> tag. The form should include an <code>input</code> and a <code>button</code>.');",
        "assert(Enzyme.mount(React.createElement(MyForm)).state('input') === '' && Enzyme.mount(React.createElement(MyForm)).state('submit') === '', 'message: The state of <code>MyForm</code> should initialize with <code>input</code> and <code>submit</code> properties, both set to empty strings.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyForm)); const _1 = () => { mockedComponent.setState({ input: '' }); return waitForIt(() => mockedComponent.state('input'))}; const _2 = () => { mockedComponent.find('input').simulate('change', { target: { value: 'TestInput' }}); return waitForIt(() => ({ state: mockedComponent.state('input'), inputVal: mockedComponent.find('input').props().value }))}; const before = await _1(); const after = await _2(); assert(before === '' && after.state === 'TestInput' && after.inputVal === 'TestInput', 'message: Typing in the <code>input</code> element should update the <code>input</code> property of the component&apos;s state.'); }; ",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyForm)); const _1 = () => { mockedComponent.setState({ input: '' }); mockedComponent.setState({submit: ''}); mockedComponent.find('input').simulate('change', {target: {value: 'SubmitInput'}}); return waitForIt(() => mockedComponent.state('submit'))}; const _2 = () => { mockedComponent.find('form').simulate('submit'); return waitForIt(() => mockedComponent.state('submit'))}; const before = await _1(); const after = await _2(); assert(before === '' && after === 'SubmitInput', 'message: Submitting the form should run <code>handleSubmit</code> which should set the <code>submit</code> property in state equal to the current input.'); };",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyForm)); const _1 = () => { mockedComponent.setState({ input: '' }); mockedComponent.setState({submit: ''}); mockedComponent.find('input').simulate('change', {target: {value: 'TestInput'}}); return waitForIt(() => mockedComponent.find('h1').text())}; const _2 = () => { mockedComponent.find('form').simulate('submit'); return waitForIt(() => mockedComponent.find('h1').text())}; const before = await _1(); const after = await _2(); assert(before === '' && after === 'TestInput', 'message: The <code>h1</code> header should render the value of the <code>submit</code> field from the component&apos;s state.'); }; "
      ],
      "solutions": [
        "class MyForm extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      input: '',\n      submit: ''\n    };\n    this.handleChange = this.handleChange.bind(this);\n    this.handleSubmit = this.handleSubmit.bind(this);\n  }\n  handleChange(event) {\n    this.setState({\n      input: event.target.value\n    });\n  }\n  handleSubmit(event) {\n    event.preventDefault()\n    this.setState({\n      submit: this.state.input\n    });\n  }\n  render() {\n    return (\n      <div>\n        <form onSubmit={this.handleSubmit}>\n          <input\n            value={this.state.input}\n            onChange={this.handleChange} />\n          <button type='submit'>Submit!</button>\n        </form>\n        <h1>{this.state.submit}</h1>\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d403617a",
      "title": "Pass State as Props to Child Components",
      "releasedOn": "December 25, 2017",
      "description": [
        "You saw a lot of examples that passed props to child JSX elements and child React components in previous challenges. You may be wondering where those props come from. A common pattern is to have a stateful component containing the <code>state</code> important to your app, that then renders child components. You want these components to have access to some pieces of that <code>state</code>, which are passed in as props.",
        "For example, maybe you have an <code>App</code> component that renders a <code>Navbar</code>, among other components. In your <code>App</code>, you have <code>state</code> that contains a lot of user information, but the <code>Navbar</code> only needs access to the user's username so it can display it. You pass that piece of <code>state</code> to the <code>Navbar</code> component as a prop.",
        "This pattern illustrates some important paradigms in React. The first is <em>unidirectional data flow</em>. State flows in one direction down the tree of your application's components, from the stateful parent component to child components. The child components only receive the state data they need. The second is that complex stateful apps can be broken down into just a few, or maybe a single, stateful component. The rest of your components simply receive state from the parent as props, and render a UI from that state. It begins to create a separation where state management is handled in one part of code and UI rendering in another. This principle of separating state logic from UI logic is one of React's key principles. When it's used correctly, it makes the design of complex, stateful applications much easier to manage.",
        "<hr>",
        "The <code>MyApp</code> component is stateful and renders a <code>Navbar</code> component as a child. Pass the <code>name</code> property in its <code>state</code> down to the child component, then show the <code>name</code> in the <code>h1</code> tag that's part of the <code>Navbar</code> render method."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class MyApp extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      name: 'CamperBot'",
            "    }",
            "  }",
            "  render() {",
            "    return (",
            "       <div>",
            "         <Navbar /* your code here */ />",
            "       </div>",
            "    );",
            "  }",
            "};",
            "",
            "class Navbar extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "  }",
            "  render() {",
            "    return (",
            "    <div>",
            "      <h1>Hello, my name is: /* your code here */ </h1>",
            "    </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<MyApp />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyApp)); return mockedComponent.find('MyApp').length === 1 && mockedComponent.find('Navbar').length === 1; })(), 'message: The <code>MyApp</code> component should render with a <code>Navbar</code> component inside.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyApp)); const setState = () => { mockedComponent.setState({name: 'TestName'}); return waitForIt(() => mockedComponent.find('Navbar').props() )}; const navProps = await setState(); assert(navProps.name === 'TestName', 'message: The <code>Navbar</code> component should receive the <code>MyApp</code> state property <code>name</code> as props.'); }; ",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyApp)); const navH1Before = mockedComponent.find('Navbar').find('h1').text(); const setState = () => { mockedComponent.setState({name: 'TestName'}); return waitForIt(() => mockedComponent.find('Navbar').find('h1').text() )}; const navH1After = await setState(); assert(new RegExp('TestName').test(navH1After) && navH1After !== navH1Before, 'message: The <code>h1</code> element in <code>Navbar</code> should render the <code>name</code> prop.'); }; "
      ],
      "solutions": [
        "class MyApp extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      name: 'CamperBot'\n    }\n  }\n  render() {\n    return (\n       <div>\n         <Navbar name={this.state.name}/>\n       </div>\n    );\n  }\n};\nclass Navbar extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n  render() {\n    return (\n    <div>\n      <h1>Hello, my name is: {this.props.name}</h1>\n    </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d403617b",
      "title": "Pass a Callback as Props",
      "releasedOn": "December 25, 2017",
      "description": [
        "You can pass <code>state</code> as props to child components, but you're not limited to passing data. You can also pass handler functions or any method that's defined on a React component to a child component. This is how you allow child components to interact with their parent components. You pass methods to a child just like a regular prop. It's assigned a name and you have access to that method name under <code>this.props</code> in the child component.",
        "<hr>",
        "There are three components outlined in the code editor. The <code>MyApp</code> component is the parent that will render the <code>GetInput</code> and <code>RenderInput</code> child components. Add the <code>GetInput</code> component to the render method in <code>MyApp</code>, then pass it a prop called <code>input</code> assigned to <code>inputValue</code> from <code>MyApp</code>&apos;s <code>state</code>. Also create a prop called <code>handleChange</code> and pass the input handler <code>handleChange</code> to it.",
        "Next, add <code>RenderInput</code> to the render method in <code>MyApp</code>, then create a prop called <code>input</code> and pass the <code>inputValue</code> from <code>state</code> to it. Once you are finished you will be able to type in the <code>input</code> field in the <code>GetInput</code> component, which then calls the handler method in its parent via props. This updates the input in the <code>state</code> of the parent, which is passed as props to both children. Observe how the data flows between the components and how the single source of truth remains the <code>state</code> of the parent component. Admittedly, this example is a bit contrived, but should serve to illustrate how data and callbacks can be passed between React components."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class MyApp extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      inputValue: ''",
            "    }",
            "    this.handleChange = this.handleChange.bind(this);",
            "  }",
            "  handleChange(event) {",
            "    this.setState({",
            "      inputValue: event.target.value",
            "    });",
            "  }",
            "  render() {",
            "    return (",
            "       <div>",
            "        { /* change code below this line */ }",
            "",
            "        { /* change code above this line */ }",
            "       </div>",
            "    );",
            "  }",
            "};",
            "",
            "class GetInput extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "  }",
            "  render() {",
            "    return (",
            "      <div>",
            "        <h3>Get Input:</h3>",
            "        <input",
            "          value={this.props.input}",
            "          onChange={this.props.handleChange}/>",
            "      </div>",
            "    );",
            "  }",
            "};",
            "",
            "class RenderInput extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "  }",
            "  render() {",
            "    return (",
            "      <div>",
            "        <h3>Input Render:</h3>",
            "        <p>{this.props.input}</p>",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<MyApp />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyApp)); return mockedComponent.find('MyApp').length === 1; })(), 'message: The <code>MyApp</code> component should render.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyApp)); return mockedComponent.find('GetInput').length === 1; })(), 'message: The <code>GetInput</code> component should render.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyApp)); return mockedComponent.find('RenderInput').length === 1; })(), 'message: The <code>RenderInput</code> component should render.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyApp)); const state_1 = () => { mockedComponent.setState({inputValue: ''}); return waitForIt(() => mockedComponent.state() )}; const state_2 = () => { mockedComponent.find('input').simulate('change', {target: {value: 'TestInput'}}); return waitForIt(() => mockedComponent.state() )}; const updated_1 = await state_1(); const updated_2 = await state_2(); assert(updated_1.inputValue === '' && updated_2.inputValue === 'TestInput', 'message: The <code>GetInput</code> component should receive the <code>MyApp</code> state property <code>inputValue</code> as props and contain an <code>input</code> element which modifies <code>MyApp</code> state.'); }; ",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyApp)); const state_1 = () => { mockedComponent.setState({inputValue: 'TestName'}); return waitForIt(() => mockedComponent )}; const updated_1 = await state_1(); assert(updated_1.find('p').text().includes('TestName'), 'message: The <code>RenderInput</code> component should receive the <code>MyApp</code> state property <code>inputValue</code> as props.'); }; "
      ],
      "solutions": [
        "class MyApp extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      inputValue: ''\n    }\n  this.handleChange = this.handleChange.bind(this);  \n  }\n  handleChange(event) {\n    this.setState({\n      inputValue: event.target.value\n    });\n  }\n  render() {\n    return (\n       <div>\n         <GetInput\n           input={this.state.inputValue}\n           handleChange={this.handleChange}/>\n         <RenderInput\n           input={this.state.inputValue}/>\n       </div>\n    );\n  }\n};\n\nclass GetInput extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n  render() {\n    return (\n      <div>\n        <h3>Get Input:</h3>\n        <input\n          value={this.props.input}\n          onChange={this.props.handleChange}/>\n      </div>\n    );\n  }\n};\n\nclass RenderInput extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n  render() {\n    return (\n      <div>\n        <h3>Input Render:</h3>\n        <p>{this.props.input}</p>\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d403617c",
      "title": "Use the Lifecycle Method componentWillMount",
      "releasedOn": "December 25, 2017",
      "description": [
        "React components have several special methods that provide opportunities to perform actions at specific points in the lifecycle of a component. These are called lifecycle methods, or lifecycle hooks, and allow you to catch components at certain points in time. This can be before they are rendered, before they update, before they receive props, before they unmount, and so on. Here is a list of some of the main lifecycle methods:",
        "<code>componentWillMount()</code>",
        "<code>componentDidMount()</code>",
        "<code>componentWillReceiveProps()</code>",
        "<code>shouldComponentUpdate()</code>",
        "<code>componentWillUpdate()</code>",
        "<code>componentDidUpdate()</code>",
        "<code>componentWillUnmount()</code>",
        "The next several lessons will cover some of the basic use cases for these lifecycle methods.",
        "<hr>",
        "The <code>componentWillMount()</code> method is called before the <code>render()</code> method when a component is being mounted to the DOM. Log something to the console within <code>componentWillMount()</code> - you may want to have your browser console open to see the output."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class MyComponent extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "  }",
            "  componentWillMount() {",
            "    // change code below this line",
            "",
            "    // change code above this line",
            "  }",
            "  render() {",
            "    return <div />",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<MyComponent />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.find('div').length === 1; })(), 'message: <code>MyComponent</code> should render a <code>div</code> element.');",
        "assert((function() { const lifecycle = React.createElement(MyComponent).type.prototype.componentWillMount.toString().replace(/ /g,''); return lifecycle.includes('console.log('); })(), 'message: <code>console.log</code> should be called in <code>componentWillMount</code>.');"
      ],
      "solutions": [
        "class MyComponent extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n  componentWillMount() {\n    // change code below this line\n    console.log('Component is mounting...');\n    // change code above this line\n  }\n  render() {\n    return <div />\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d403617d",
      "title": "Use the Lifecycle Method componentDidMount",
      "releasedOn": "December 25, 2017",
      "description": [
        "Most web developers, at some point, need to call an API endpoint to retrieve data. If you're working with React, it's important to know where to perform this action.",
        "The best practice with React is to place API calls or any calls to your server in the lifecycle method <code>componentDidMount()</code>. This method is called after a component is mounted to the DOM. Any calls to <code>setState()</code> here will trigger a re-rendering of your component. When you call an API in this method, and set your state with the data that the API returns, it will automatically trigger an update once you receive the data.",
        "<hr>",
        "There is a mock API call in <code>componentDidMount()</code>. It sets state after 2.5 seconds to simulate calling a server to retrieve data. This example requests the current total active users for a site. In the render method, render the value of <code>activeUsers</code> in the <code>h1</code>. Watch what happens in the preview, and feel free to change the timeout to see the different effects."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class MyComponent extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      activeUsers: null",
            "    };",
            "  }",
            "  componentDidMount() {",
            "    setTimeout( () => {",
            "      this.setState({",
            "        activeUsers: 1273",
            "      });",
            "    }, 2500);",
            "  }",
            "  render() {",
            "    return (",
            "      <div>",
            "        <h1>Active Users: { /* change code here */ }</h1>",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<MyComponent />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return (mockedComponent.find('div').length === 1 && mockedComponent.find('h1').length === 1); })(), 'message: <code>MyComponent</code> should render a <code>div</code> element which wraps an <code>h1</code> tag.');",
        "assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return new RegExp('setTimeout(.|\\n)+setState(.|\\n)+activeUsers').test(String(mockedComponent.instance().componentDidMount)); })(), 'message: Component state should be updated with a timeout function in <code>componentDidMount</code>.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ activeUsers: 1237 }); return waitForIt(() => mockedComponent.find('h1').text()); }; const second = () => { mockedComponent.setState({ activeUsers: 1000 }); return waitForIt(() => mockedComponent.find('h1').text()); }; const firstValue = await first(); const secondValue = await second(); assert(new RegExp('1237').test(firstValue) && new RegExp('1000').test(secondValue), 'message: The <code>h1</code> tag should render the <code>activeUsers</code> value from <code>MyComponent</code>&apos;s state.'); }; "
      ],
      "solutions": [
        "class MyComponent extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      activeUsers: null\n    };\n  }\n  componentDidMount() {\n    setTimeout( () => {\n      this.setState({\n        activeUsers: 1273\n      });\n    }, 2500);\n  }\n  render() {\n    return (\n      <div>\n        <h1>Active Users: {this.state.activeUsers}</h1>\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d403617e",
      "title": "Add Event Listeners",
      "releasedOn": "December 25, 2017",
      "description": [
        "The <code>componentDidMount()</code> method is also the best place to attach any event listeners you need to add for specific functionality. React provides a synthetic event system which wraps the native event system present in browsers. This means that the synthetic event system behaves exactly the same regardless of the user's browser - even if the native events may behave differently between different browsers.",
        "You've already been using some of these synthetic event handlers such as <code>onClick()</code>. React's synthetic event system is great to use for most interactions you'll manage on DOM elements. However, if you want to attach an event handler to the document or window objects, you have to do this directly.",
        "<hr>",
        "Attach an event listener in the <code>componentDidMount()</code> method for <code>keydown</code> events and have these events trigger the callback <code>handleKeyPress()</code>. You can use <code>document.addEventListener()</code> which takes the event (in quotes) as the first argument and the callback as the second argument.",
        "Then, in <code>componentWillUnmount()</code>, remove this same event listener. You can pass the same arguments to <code>document.removeEventListener()</code>. It's good practice to use this lifecycle method to do any clean up on React components before they are unmounted and destroyed. Removing event listeners is an example of one such clean up action."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class MyComponent extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      message: ''",
            "    };",
            "    this.handleEnter = this.handleEnter.bind(this);",
            "    this.handleKeyPress = this.handleKeyPress.bind(this);",
            "  }",
            "  // change code below this line",
            "  componentDidMount() {",
            "",
            "  }",
            "  componentWillUnmount() {",
            "",
            "  }",
            "  // change code above this line",
            "  handleEnter() {",
            "    this.setState({",
            "      message: this.state.message + 'You pressed the enter key! '",
            "    });",
            "  }",
            "  handleKeyPress(event) {",
            "    if (event.keyCode === 13) {",
            "      this.handleEnter();",
            "    }",
            "  }",
            "  render() {",
            "    return (",
            "      <div>",
            "        <h1>{this.state.message}</h1>",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<MyComponent />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.find('div').children().find('h1').length === 1; })(), 'message: <code>MyComponent</code> should render a <code>div</code> element which wraps an <code>h1</code> tag.');",
        "assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const didMountString = mockedComponent.instance().componentDidMount.toString(); return new RegExp('document\\.addEventListener(.|\\n|\\r)+keydown(.|\\n|\\r)+this\\.handleKeyPress').test(didMountString); })(), 'message: A keydown listener should be attached to the document in <code>componentDidMount</code>.');",
        "assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const willUnmountString = mockedComponent.instance().componentWillUnmount.toString(); return new RegExp('document\\.removeEventListener(.|\\n|\\r)+keydown(.|\\n|\\r)+this\\.handleKeyPress').test(willUnmountString); })(), 'message: The keydown listener should be removed from the document in <code>componentWillUnmount</code>.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const beforeState = mockedComponent.state('message'); const beforeText = mockedComponent.find('h1').text(); const pressEnterKey = () => { mockedComponent.instance().handleKeyPress({ keyCode: 13 }); return waitForIt(() => { mockedComponent.update(); return { state: mockedComponent.state('message'), text: mockedComponent.find('h1').text()}; });}; const afterKeyPress = await pressEnterKey(); assert(beforeState !== afterKeyPress.state && beforeText !== afterKeyPress.text, 'message: Once the component has mounted, pressing <code>enter</code> should update its state and the rendered <code>h1</code> tag.'); }; "
      ],
      "solutions": [
        "class MyComponent extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      message: ''\n    };\n    this.handleKeyPress = this.handleKeyPress.bind(this);\n    this.handleEnter = this.handleEnter.bind(this);  }\n  componentDidMount() {\n    // change code below this line\n    document.addEventListener('keydown', this.handleKeyPress);\n    // change code above this line\n  }\n  componentWillUnmount() {\n    // change code below this line\n    document.removeEventListener('keydown', this.handleKeyPress);\n    // change code above this line\n  }\n  handleEnter() {\n    this.setState({\n      message: this.state.message + 'You pressed the enter key! '\n    });\n  }\n  handleKeyPress(event) {\n    if (event.keyCode === 13) {\n      this.handleEnter();\n    }\n  }\n  render() {\n    return (\n      <div>\n        <h1>{this.state.message}</h1>\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d403617f",
      "title": "Manage Updates with Lifecycle Methods",
      "releasedOn": "December 25, 2017",
      "description": [
        "Another lifecycle method is <code>componentWillReceiveProps()</code> which is called whenever a component is receiving new props. This method receives the new props as an argument, which is usually written as <code>nextProps</code>. You can use this argument and compare with <code>this.props</code> and perform actions before the component updates. For example, you may call <code>setState()</code> locally before the update is processed.",
        "Another method is <code>componentDidUpdate()</code>, and is called immediately after a component re-renders. Note that rendering and mounting are considered different things in the component lifecycle. When a page first loads, all components are mounted and this is where methods like <code>componentWillMount()</code> and <code>componentDidMount()</code> are called. After this, as state changes, components re-render themselves. The next challenge covers this in more detail.",
        "<hr>",
        "The child component <code>Dialog</code> receives <code>message</code> props from its parent, the <code>Controller</code> component. Write the <code>componentWillReceiveProps()</code> method in the <code>Dialog</code> component and have it log <code>this.props</code> and <code>nextProps</code> to the console. You'll need to pass <code>nextProps</code> as an argument to this method and although it's possible to name it anything, name it <code>nextProps</code> here.",
        "Next, add <code>componentDidUpdate()</code> in the <code>Dialog</code> component, and log a statement that says the component has updated. This method works similar to <code>componentWillUpdate()</code>, which is provided for you. Now click the button to change the message and watch your browser console. The order of the console statements show the order the methods are called.",
        "<strong>Note:</strong>&nbsp;You'll need to write the lifecycle methods as normal functions and not as arrow functions to pass the tests (there is also no advantage to writing lifecycle methods as arrow functions)."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class Dialog extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "  }",
            "  componentWillUpdate() {",
            "    console.log('Component is about to update...');",
            "  }",
            "  // change code below this line",
            "",
            "  // change code above this line",
            "  render() {",
            "    return <h1>{this.props.message}</h1>",
            "  }",
            "};",
            "",
            "class Controller extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      message: 'First Message'",
            "    };",
            "    this.changeMessage = this.changeMessage.bind(this);",
            "  }",
            "  changeMessage() {",
            "    this.setState({",
            "      message: 'Second Message'",
            "    });",
            "  }",
            "  render() {",
            "    return (",
            "      <div>",
            "        <button onClick={this.changeMessage}>Update</button>",
            "        <Dialog message={this.state.message}/>",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<Controller />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Controller)); return mockedComponent.find('Controller').length === 1 && mockedComponent.find('Dialog').length === 1; })(), 'message: The <code>Controller</code> component should render the <code>Dialog</code> component as a child.');",
        "assert((function() { const lifecycleChild = React.createElement(Dialog).type.prototype.componentWillReceiveProps.toString().replace(/ /g,''); return lifecycleChild.includes('console.log') && lifecycleChild.includes('this.props') })(), 'message: The <code>componentWillReceiveProps</code> method in the <code>Dialog</code> component should log <code>this.props</code> to the console.');",
        "assert((function() { const lifecycleChild = React.createElement(Dialog).type.prototype.componentWillReceiveProps.toString().replace(/ /g,''); const nextPropsAsParameterTest = \/componentWillReceiveProps(| *?= *?)(\\(|)nextProps(\\)|)( *?=> *?{| *?{|{)\/; const nextPropsInConsoleLogTest = \/console\\.log\\(.*?nextProps\\b.*?\\)\/; return ( lifecycleChild.includes('console.log') && nextPropsInConsoleLogTest.test(lifecycleChild) && nextPropsAsParameterTest.test(lifecycleChild) ); })(), 'message: The <code>componentWillReceiveProps</code> method in the <code>Dialog</code> component should log <code>nextProps</code> to the console.');",
        "assert((function() { const lifecycleChild = React.createElement(Dialog).type.prototype.componentDidUpdate.toString().replace(/ /g,''); return lifecycleChild.length !== 'undefined' && lifecycleChild.includes('console.log'); })(), 'message: The <code>Dialog</code> component should call the <code>componentDidUpdate</code> method and log a message to the console.');"
      ],
      "solutions": [
        "class Dialog extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n  componentWillUpdate() {\n    console.log('Component is about to update...');\n  }\n  // change code below this line\n  componentWillReceiveProps(nextProps) {\n    console.log(this.props, nextProps);\n  }\n  componentDidUpdate() {\n    console.log('Component re-rendered');\n  }\n  // change code above this line\n  render() {\n    return <h1>{this.props.message}</h1>\n  }\n};\n\nclass Controller extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      message: 'First Message'\n    };\n this.changeMessage = this.changeMessage.bind(this); \n  }\n  changeMessage() {\n    this.setState({\n      message: 'Second Message'\n    });\n  }\n  render() {\n    return (\n      <div>\n        <button onClick={this.changeMessage}>Update</button>\n        <Dialog message={this.state.message}/>\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036180",
      "title": "Optimize Re-Renders with shouldComponentUpdate",
      "releasedOn": "December 25, 2017",
      "description": [
        "So far, if any component receives new <code>state</code> or new <code>props</code>, it re-renders itself and all its children. This is usually okay. But React provides a lifecycle method you can call when child components receive new <code>state</code> or <code>props</code>, and declare specifically if the components should update or not. The method is <code>shouldComponentUpdate()</code>, and it takes <code>nextProps</code> and <code>nextState</code> as parameters.",
        "This method is a useful way to optimize performance. For example, the default behavior is that your component re-renders when it receives new <code>props</code>, even if the <code>props</code> haven't changed. You can use <code>shouldComponentUpdate()</code> to prevent this by comparing the <code>props</code>. The method must return a <code>boolean</code> value that tells React whether or not to update the component. You can compare the current props (<code>this.props</code>) to the next props (<code>nextProps</code>) to determine if you need to update or not, and return <code>true</code> or <code>false</code> accordingly.",
        "<hr>",
        "The <code>shouldComponentUpdate()</code> method is added in a component called <code>OnlyEvens</code>. Currently, this method returns <code>true</code> so <code>OnlyEvens</code> re-renders every time it receives new <code>props</code>. Modify the method so <code>OnlyEvens</code> updates only if the <code>value</code> of its new props is even. Click the <code>Add</code> button and watch the order of events in your browser's console as the other lifecycle hooks are triggered."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class OnlyEvens extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "  }",
            "  shouldComponentUpdate(nextProps, nextState) {",
            "    console.log('Should I update?');",
            "     // change code below this line",
            "    return true;",
            "     // change code above this line",
            "  }",
            "  componentWillReceiveProps(nextProps) {",
            "    console.log('Receiving new props...');",
            "  }",
            "  componentDidUpdate() {",
            "    console.log('Component re-rendered.');",
            "  }",
            "  render() {",
            "    return <h1>{this.props.value}</h1>",
            "  }",
            "};",
            "",
            "class Controller extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      value: 0",
            "    };",
            "    this.addValue = this.addValue.bind(this);",
            "  }",
            "  addValue() {",
            "    this.setState({",
            "      value: this.state.value + 1",
            "    });",
            "  }",
            "  render() {",
            "    return (",
            "      <div>",
            "        <button onClick={this.addValue}>Add</button>",
            "        <OnlyEvens value={this.state.value}/>",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<Controller />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((() => { const mockedComponent = Enzyme.mount(React.createElement(Controller)); return mockedComponent.find('Controller').length === 1 && mockedComponent.find('OnlyEvens').length === 1; })(), 'message: The <code>Controller</code> component should render the <code>OnlyEvens</code> component as a child.');",
        "assert((() => { const child = React.createElement(OnlyEvens).type.prototype.shouldComponentUpdate.toString().replace(/s/g,''); return child !== 'undefined'; })(), 'message: The <code>shouldComponentUpdate</code> method should be defined on the <code>OnlyEvens</code> component.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(Controller)); const first = () => { mockedComponent.setState({ value: 1000 }); return waitForIt(() => mockedComponent.find('h1').html()); }; const second = () => { mockedComponent.setState({ value: 10 }); return waitForIt(() => mockedComponent.find('h1').html()); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === '<h1>1000</h1>' && secondValue === '<h1>10</h1>', 'message: The <code>OnlyEvens</code> component should return an <code>h1</code> tag which renders the value of <code>this.props.value</code>.'); }; ",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(Controller)); const first = () => { mockedComponent.setState({ value: 8 }); return waitForIt(() => mockedComponent.find('h1').text()); }; const second = () => { mockedComponent.setState({ value: 7 }); return waitForIt(() => mockedComponent.find('h1').text()); }; const third = () => { mockedComponent.setState({ value: 42 }); return waitForIt(() => mockedComponent.find('h1').text()); }; const firstValue = await first(); const secondValue = await second(); const thirdValue = await third(); assert(firstValue === '8' && secondValue === '8' && thirdValue === '42', 'message: <code>OnlyEvens</code> should re-render only when <code>nextProps.value</code> is even.'); }; "
      ],
      "solutions": [
        "class OnlyEvens extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n  shouldComponentUpdate(nextProps, nextState) {\n    console.log('Should I update?');\n    // change code below this line\n    return nextProps.value % 2 === 0;\n    // change code above this line\n  }\n  componentWillReceiveProps(nextProps) {\n    console.log('Receiving new props...');\n  }\n  componentDidUpdate() {\n    console.log('Component re-rendered.');\n  }\n  render() {\n    return <h1>{this.props.value}</h1>\n  }\n};\n\nclass Controller extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      value: 0\n    };\n  this.addValue = this.addValue.bind(this);\n  }\n  addValue() {\n    this.setState({\n      value: this.state.value + 1\n    });\n  }\n  render() {\n    return (\n      <div>\n        <button onClick={this.addValue}>Add</button>\n        <OnlyEvens value={this.state.value}/>\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036181",
      "title": "Introducing Inline Styles",
      "releasedOn": "December 25, 2017",
      "description": [
        "There are other complex concepts that add powerful capabilities to your React code. But you may be wondering about the more simple problem of how to style those JSX elements you create in React. You likely know that it won't be exactly the same as working with HTML because of <a target=\"_blank\" href=\"link to classes challenge\"> the way you apply classes to JSX elements</a>.",
        "If you import styles from a stylesheet, it isn't much different at all. You apply a class to your JSX element using the <code>className</code> attribute, and apply styles to the class in your stylesheet. Another option is to apply <strong><em>inline</em></strong> styles, which are very common in ReactJS development.",
        "You apply inline styles to JSX elements similar to how you do it in HTML, but with a few JSX differences. Here's an example of an inline style in HTML:",
        "<code>&lt;div style=\"color: yellow; font-size: 16px\"&gt;Mellow Yellow&lt;/div&gt;</code>",
        "JSX elements use the <code>style</code> attribute, but because of the way JSX is transpiled, you can't set the value to a <code>string</code>. Instead, you set it equal to a JavaScript <code>object</code>. Here's an example:",
        "<code>&lt;div style={{color: \"yellow\", fontSize: 16}}&gt;Mellow Yellow&lt;/div&gt;</code>",
        "<hr>",
        "Add a <code>style</code> attribute to the <code>div</code> in the code editor to give the text a color of red and font size of 72px.",
        "Note that you can optionally set the font size to be a number, omitting the units \"px\", or write it as \"72px\"."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "",
            "class Colorful extends React.Component {",
            "  render() {",
            "    return (",
            "      <div>Big Red</div>",
            "    );",
            "  }",
            "};",
            ""
          ],
          "tail": "ReactDOM.render(<Colorful />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Colorful)); return mockedComponent.children().type() === 'div'; })(), 'message: The component should render a <code>div</code> element.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Colorful)); return mockedComponent.children().props().style.color === 'red'; })(), 'message: The <code>div</code> element should have a color of <code>red</code>.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Colorful)); return (mockedComponent.children().props().style.fontSize === 72 || mockedComponent.children().props().style.fontSize === '72' || mockedComponent.children().props().style.fontSize === '72px'); })(), 'message: The <code>div</code> element should have a font size of <code>72px</code>.');"
      ],
      "solutions": [
        "\nclass Colorful extends React.Component {\n  render() {\n    return (\n      <div style={{color: \"red\", fontSize: 72}}>Big Red</div>\n    );\n  }\n};\n"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036182",
      "title": "Add Inline Styles in React",
      "releasedOn": "December 25, 2017",
      "description": [
        "You may have noticed in the last challenge that there were several other syntax differences from HTML inline styles in addition to the <code>style</code> attribute set to a JavaScript object. First, the names of certain CSS style properties use camel case. For example, the last challenge set the size of the font with <code>fontSize</code> instead of <code>font-size</code>. Hyphenated words like <code>font-size</code> are invalid syntax for JavaScript object properties, so React uses camel case. As a rule, any hyphenated style properties are written using camel case in JSX.",
        "All property value length units (like <code>height</code>, <code>width</code>, and <code>fontSize</code>) are assumed to be in <code>px</code> unless otherwise specified. If you want to use <code>em</code>, for example, you wrap the value and the units in quotes, like <code>{fontSize: \"4em\"}</code>. Other than the length values that default to <code>px</code>, all other property values should be wrapped in quotes.",
        "<hr>",
        "If you have a large set of styles, you can assign a style <code>object</code> to a constant to keep your code organized. Uncomment the <code>styles</code> constant and declare an <code>object</code> with three style properties and their values. Give the <code>div</code> a color of <code>\"purple\"</code>, a font-size of <code>40</code>, and a border of <code>\"2px solid purple\"</code>. Then set the <code>style</code> attribute equal to the <code>styles</code> constant."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "",
            "// const styles =",
            "// change code above this line",
            "class Colorful extends React.Component {",
            "  render() {",
            "    // change code below this line",
            "    return (",
            "      <div style={{color: \"yellow\", fontSize: 24}}>Style Me!</div>",
            "    );",
            "    // change code above this line",
            "  }",
            "};",
            ""
          ],
          "tail": "ReactDOM.render(<Colorful />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert(Object.keys(styles).length === 3, 'message: The <code>styles</code> variable should be an <code>object</code> with three properties.');",
        "assert(styles.color === 'purple', 'message: The <code>styles</code> variable should have a <code>color</code> property set to a value of <code>purple</code>.');",
        "assert(styles.fontSize === 40, 'message: The <code>styles</code> variable should have a <code>fontSize</code> property set to a value of <code>40</code>.');",
        "assert(styles.border === \"2px solid purple\", 'message: The <code>styles</code> variable should have a <code>border</code> property set to a value of <code>2px solid purple</code>.');",
        "assert((function() { const mockedComponent = Enzyme.shallow(React.createElement(Colorful)); return mockedComponent.type() === 'div'; })(), 'message: The component should render a <code>div</code> element.');",
        "assert((function() { const mockedComponent = Enzyme.shallow(React.createElement(Colorful)); return (mockedComponent.props().style.color === \"purple\" && mockedComponent.props().style.fontSize === 40 && mockedComponent.props().style.border === \"2px solid purple\"); })(), 'message: The <code>div</code> element should have its styles defined by the <code>styles</code> object.');"
      ],
      "solutions": [
        "\nconst styles = {\n  color: \"purple\",\n  fontSize: 40,\n  border: \"2px solid purple\"\n};\n// change code above this line\nclass Colorful extends React.Component {\n  render() {\n    // change code below this line\n    return (\n      <div style={styles}>Style Me!</div>\n  // change code above this line\n    );\n  }\n};\n"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036183",
      "title": "Use Advanced JavaScript in React Render Method",
      "releasedOn": "December 25, 2017",
      "description": [
        "In previous challenges, you learned how to inject JavaScript code into JSX code using curly braces, <code>{ }</code>, for tasks like accessing props, passing props, accessing state, inserting comments into your code, and most recently, styling your components. These are all common use cases to put JavaScript in JSX, but they aren't the only way that you can utilize JavaScript code in your React components.",
        "You can also write JavaScript directly in your <code>render</code> methods, before the <code>return</code> statement, <strong><em>without</em></strong> inserting it inside of curly braces. This is because it is not yet within the JSX code. When you want to use a variable later in the JSX code <em>inside</em> the <code>return</code> statement, you place the variable name inside curly braces.",
        "<hr>",
        "In the code provided, the <code>render</code> method has an array that contains 20 phrases to represent the answers found in the classic 1980's Magic Eight Ball toy. The button click event is bound to the <code>ask</code> method, so each time the button is clicked a random number will be generated and stored as the <code>randomIndex</code> in state. On line 52, delete the string <code>\"change me!\"</code> and reassign the <code>answer</code> const so your code randomly accesses a different index of the <code>possibleAnswers</code> array each time the component updates. Finally, insert the <code>answer</code> const inside the <code>p</code> tags."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "const inputStyle = {",
            "  width: 235,",
            "  margin: 5",
            "}",
            "",
            "class MagicEightBall extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      userInput: '',",
            "      randomIndex: ''",
            "    }",
            "    this.ask = this.ask.bind(this);",
            "    this.handleChange = this.handleChange.bind(this);",
            "  }",
            "  ask() {",
            "    if (this.state.userInput) {",
            "      this.setState({",
            "        randomIndex: Math.floor(Math.random() * 20),",
            "        userInput: ''",
            "      });",
            "    }",
            "  }",
            "  handleChange(event) {",
            "    this.setState({",
            "      userInput: event.target.value",
            "    });",
            "  }",
            "  render() {",
            "    const possibleAnswers = [",
            "      'It is certain',",
            "      'It is decidedly so',",
            "      'Without a doubt', ",
            "      'Yes, definitely',",
            "      'You may rely on it',",
            "      'As I see it, yes',",
            "      'Outlook good',",
            "      'Yes',",
            "      'Signs point to yes',",
            "      'Reply hazy try again',",
            "      'Ask again later',",
            "      'Better not tell you now',",
            "      'Cannot predict now',",
            "      'Concentrate and ask again',",
            "      'Don\\'t count on it', ",
            "      'My reply is no',",
            "      'My sources say no',",
            "      'Most likely',",
            "      'Outlook not so good',",
            "      'Very doubtful'",
            "    ];",
            "    const answer = 'change me!' // << change code here",
            "    return (",
            "      <div>",
            "        <input",
            "          type=\"text\"",
            "          value={this.state.userInput}",
            "          onChange={this.handleChange}",
            "          style={inputStyle} /><br />",
            "        <button onClick={this.ask}>",
            "          Ask the Magic Eight Ball!",
            "        </button><br />",
            "        <h3>Answer:</h3>",
            "        <p>",
            "          { /* change code below this line */ }",
            "",
            "          { /* change code above this line */ }",
            "        </p>",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": [
            "var possibleAnswers = [ 'It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely', 'You may rely on it', 'As I see it, yes', 'Outlook good', 'Yes', 'Signs point to yes', 'Reply hazy try again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again', 'Don\\'t count on it', 'My reply is no', 'My sources say no', 'Outlook not so good','Very doubtful', 'Most likely' ];",
            "ReactDOM.render(<MagicEightBall />, document.getElementById('root'))"
          ]
        }
      },
      "tests": [
        "assert.strictEqual(Enzyme.mount(React.createElement(MagicEightBall)).find('MagicEightBall').length, 1, 'message: The <code>MagicEightBall</code> component should exist and should render to the page.');",
        "assert.strictEqual(Enzyme.mount(React.createElement(MagicEightBall)).children().childAt(0).name(), 'input', 'message: <code>MagicEightBall</code>&apos;s first child should be an <code>input</code> element.');",
        "assert.strictEqual(Enzyme.mount(React.createElement(MagicEightBall)).children().childAt(2).name(), 'button', 'message: <code>MagicEightBall</code>&apos;s third child should be a <code>button</code> element.');",
        "assert(Enzyme.mount(React.createElement(MagicEightBall)).state('randomIndex') === '' && Enzyme.mount(React.createElement(MagicEightBall)).state('userInput') === '', 'message: <code>MagicEightBall</code>&apos;s state should be initialized with a property of <code>userInput</code> and a property of <code>randomIndex</code> both set to a value of an empty string.');",
        "assert(Enzyme.mount(React.createElement(MagicEightBall)).find('p').length === 1 && Enzyme.mount(React.createElement(MagicEightBall)).find('p').text() === '', 'message: When <code>MagicEightBall</code> is first mounted to the DOM, it should return an empty <code>p</code> element.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const comp = Enzyme.mount(React.createElement(MagicEightBall)); const simulate = () => { comp.find('input').simulate('change', { target: { value: 'test?' }}); comp.find('button').simulate('click'); }; const result = () => comp.find('p').text(); const _1 = () => { simulate(); return waitForIt(() => result()) }; const _2 = () => { simulate(); return waitForIt(() => result()) }; const _3 = () => { simulate(); return waitForIt(() => result()) }; const _4 = () => { simulate(); return waitForIt(() => result()) }; const _5 = () => { simulate(); return waitForIt(() => result()) }; const _6 = () => { simulate(); return waitForIt(() => result()) }; const _7 = () => { simulate(); return waitForIt(() => result()) }; const _8 = () => { simulate(); return waitForIt(() => result()) }; const _9 = () => { simulate(); return waitForIt(() => result()) }; const _10 = () => { simulate(); return waitForIt(() => result()) }; const _1_val = await _1(); const _2_val = await _2(); const _3_val = await _3(); const _4_val = await _4(); const _5_val = await _5(); const _6_val = await _6(); const _7_val = await _7(); const _8_val = await _8(); const _9_val = await _9(); const _10_val = await _10(); const actualAnswers = [_1_val, _2_val, _3_val, _4_val, _5_val, _6_val, _7_val, _8_val, _9_val, _10_val]; const hasIndex = actualAnswers.filter((answer, i) => possibleAnswers.indexOf(answer) !== -1); const notAllEqual = new Set(actualAnswers); assert(notAllEqual.size > 1 && hasIndex.length === 10, 'message: When text is entered into the <code>input</code> element and the button is clicked, the <code>MagicEightBall</code> component should return a <code>p</code> element that contains a random element from the <code>possibleAnswers</code> array.');}"
      ],
      "solutions": [
        "\nconst inputStyle = {\n  width: 235,\n  margin: 5\n}\n\nclass MagicEightBall extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      userInput: '',\n      randomIndex: ''\n    }\n    this.ask = this.ask.bind(this);\n    this.handleChange = this.handleChange.bind(this);\n  }\n  ask() {\n    if (this.state.userInput) {\n      this.setState({\n        randomIndex: Math.floor(Math.random() * 20),\n        userInput: ''\n      });\n    }\n  }\n  handleChange(event) {\n    this.setState({\n      userInput: event.target.value\n    });\n  }\n  render() {\n    const possibleAnswers = [\n      \"It is certain\", \"It is decidedly so\", \"Without a doubt\",\n      \"Yes, definitely\", \"You may rely on it\", \"As I see it, yes\",\n      \"Outlook good\", \"Yes\", \"Signs point to yes\", \"Reply hazy try again\",\n      \"Ask again later\", \"Better not tell you now\", \"Cannot predict now\",\n      \"Concentrate and ask again\", \"Don't count on it\", \"My reply is no\",\n      \"My sources say no\", \"Outlook not so good\",\"Very doubtful\", \"Most likely\"\n    ];\n    const answer = possibleAnswers[this.state.randomIndex];\n    return (\n      <div>\n        <input\n          type=\"text\"\n          value={this.state.userInput}\n          onChange={this.handleChange}\n          style={inputStyle} /><br />\n        <button onClick={this.ask}>Ask the Magic Eight Ball!</button><br />\n        <h3>Answer:</h3>\n        <p>\n          {answer}\n        </p>\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036184",
      "title": "Render with an If/Else Condition",
      "releasedOn": "December 25, 2017",
      "description": [
        "Another application of using JavaScript to control your rendered view is to tie the elements that are rendered to a condition. When the condition is true, one view renders, when it's false, it's a different view. You can do this with a standard <code>if/else</code> statement in the <code>render()</code> method of a React component.",
        "<hr>",
        "MyComponent contains a <code>boolean</code> in its state which tracks whether you want to display some element in the UI or not. The <code>button</code> toggles the state of this value. Currently, it renders the same UI every time. Rewrite the <code>render()</code> method with an <code>if/else</code> statement so that if <code>display</code> is <code>true</code>, you return the current markup. Otherwise, return the markup without the <code>h1</code> element.",
        "<strong>Note:</strong>&nbsp;You must write an <code>if/else</code> to pass the tests, use of the ternary operator will not pass here."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class MyComponent extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      display: true",
            "    }",
            "    this.toggleDisplay = this.toggleDisplay.bind(this);",
            "  }",
            "  toggleDisplay() {",
            "    this.setState({",
            "      display: !this.state.display",
            "    });",
            "  }",
            "  render() {",
            "    // change code below this line",
            "",
            "    return (",
            "       <div>",
            "         <button onClick={this.toggleDisplay}>Toggle Display</button>",
            "         <h1>Displayed!</h1>",
            "       </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<MyComponent />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.find('MyComponent').length === 1; })(), 'message: <code>MyComponent</code> should exist and render.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const state_1 = () => { mockedComponent.setState({display: true}); return waitForIt(() => mockedComponent )}; const updated = await state_1(); assert(mockedComponent.find('div').length === 1 && mockedComponent.find('div').children().length === 2 && mockedComponent.find('button').length === 1 && mockedComponent.find('h1').length === 1, 'message: When <code>display</code> is set to <code>true</code>, a <code>div</code>, <code>button</code>, and <code>h1</code> should render.'); }; ",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const state_1 = () => { mockedComponent.setState({display: false}); return waitForIt(() => mockedComponent )}; const updated = await state_1(); assert(mockedComponent.find('div').length === 1 && mockedComponent.find('div').children().length === 1 && mockedComponent.find('button').length === 1 && mockedComponent.find('h1').length === 0, 'message: When <code>display</code> is set to <code>false</code>, only a <code>div</code> and <code>button</code> should render.'); }; ",
        "getUserInput => assert(getUserInput('index').includes('if') && getUserInput('index').includes('else'), 'message: The render method should use an <code>if/else</code> statement to check the condition of <code>this.state.display</code>.');"
      ],
      "solutions": [
        "class MyComponent extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      display: true\n    }\n this.toggleDisplay = this.toggleDisplay.bind(this); \n }\n  toggleDisplay() {\n    this.setState({\n      display: !this.state.display\n    });\n  }\n  render() {\n    // change code below this line\n    if (this.state.display) {\n      return (\n         <div>\n           <button onClick={this.toggleDisplay}>Toggle Display</button>\n           <h1>Displayed!</h1>\n         </div>\n      );\n    } else {\n      return (\n        <div>\n           <button onClick={this.toggleDisplay}>Toggle Display</button>\n         </div>\n      );\n    }\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036185",
      "title": "Use && for a More Concise Conditional",
      "releasedOn": "December 25, 2017",
      "description": [
        "The if/else statements worked in the last challenge, but there's a more concise way to achieve the same result. Imagine that you are tracking several conditions in a component and you want different elements to render depending on each of these conditions. If you write a lot of <code>else if</code> statements to return slightly different UIs, you may repeat code which leaves room for error. Instead, you can use the <code>&&</code> logical operator to perform conditional logic in a more concise way. This is possible because you want to check if a condition is <code>true</code>, and if it is, return some markup. Here's an example:",
        "<code>{condition && &lt;p&gt;markup&lt;/p&gt;}</code>",
        "If the <code>condition</code> is <code>true</code>, the markup will be returned. If the condition is <code>false</code>, the operation will immediately return <code>false</code> after evaluating the <code>condition</code> and return nothing. You can include these statements directly in your JSX and string multiple conditions together by writing <code>&&</code> after each one. This allows you to handle more complex conditional logic in your <code>render()</code> method without repeating a lot of code.",
        "<hr>",
        "Solve the previous example again, so the <code>h1</code> only renders if <code>display</code> is <code>true</code>, but use the <code>&&</code> logical operator instead of an <code>if/else</code> statement."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class MyComponent extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      display: true",
            "    }",
            "    this.toggleDisplay = this.toggleDisplay.bind(this);",
            "  }",
            "  toggleDisplay() {",
            "    this.setState({",
            "      display: !this.state.display",
            "    });",
            "  }",
            "  render() {",
            "    // change code below this line",
            "    return (",
            "       <div>",
            "         <button onClick={this.toggleDisplay}>Toggle Display</button>",
            "         <h1>Displayed!</h1>",
            "       </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<MyComponent />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.find('MyComponent').length; })(), 'message: <code>MyComponent</code> should exist and render.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const state_1 = () => { mockedComponent.setState({display: true}); return waitForIt(() => mockedComponent )}; const updated = await state_1(); assert(updated.find('div').length === 1 && updated.find('div').children().length === 2 && updated.find('button').length === 1 && updated.find('h1').length === 1, 'message: When <code>display</code> is set to <code>true</code>, a <code>div</code>, <code>button</code>, and <code>h1</code> should render.'); }; ",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const state_1 = () => { mockedComponent.setState({display: false}); return waitForIt(() => mockedComponent )}; const updated = await state_1(); assert(updated.find('div').length === 1 && updated.find('div').children().length === 1 && updated.find('button').length === 1 && updated.find('h1').length === 0, 'message: When <code>display</code> is set to <code>false</code>, only a <code>div</code> and <code>button</code> should render.'); }; ",
        "getUserInput => assert(getUserInput('index').includes('&&'), 'message: The render method should use the && logical operator to check the condition of this.state.display.');"
      ],
      "solutions": [
        "class MyComponent extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      display: true\n    }\n this.toggleDisplay = this.toggleDisplay.bind(this); \n  }\n  toggleDisplay() {\n    this.setState({\n      display: !this.state.display\n    });\n  }\n  render() {\n    // change code below this line\n    return (\n       <div>\n         <button onClick={this.toggleDisplay}>Toggle Display</button>\n         {this.state.display && <h1>Displayed!</h1>}\n       </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036187",
      "title": "Use a Ternary Expression for Conditional Rendering",
      "releasedOn": "December 25, 2017",
      "description": [
        "Before moving on to dynamic rendering techniques, there's one last way to use built-in JavaScript conditionals to render what you want: the <em><strong>ternary operator</strong></em>. The ternary operator is often utilized as a shortcut for <code>if/else</code> statements in JavaScript. They're not quite as robust as traditional <code>if/else</code> statements, but they are very popular among React developers. One reason for this is because of how JSX is compiled, <code>if/else</code> statements can't be inserted directly into JSX code. You might have noticed this a couple challenges ago &mdash; when an <code>if/else</code> statement was required, it was always <em>outside</em> the <code>return</code> statement. Ternary expressions can be an excellent alternative if you want to implement conditional logic within your JSX. Recall that a ternary operator has three parts, but you can combine several ternary expressions together. Here's the basic syntax:",
        "<blockquote>condition ? expressionIfTrue : expressionIfFalse</blockquote>",
        "<hr>",
        "The code editor has three constants defined within the <code>CheckUserAge</code> component's <code>render()</code> method. They are called <code>buttonOne</code>, <code>buttonTwo</code>, and <code>buttonThree</code>. Each of these is assigned a simple JSX expression representing a button element. First, initialize the state of <code>CheckUserAge</code> with <code>input</code> and <code>userAge</code> both set to values of an empty string.",
        "Once the component is rendering information to the page, users should have a way to interact with it. Within the component's <code>return</code> statement, set up a ternary expression that implements the following logic: when the page first loads, render the submit button, <code>buttonOne</code>, to the page. Then, when a user enters their age and clicks the button, render a different button based on the age. If a user enters a number less than <code>18</code>, render <code>buttonThree</code>. If a user enters a number greater than or equal to <code>18</code>, render <code>buttonTwo</code>."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "",
            "const inputStyle = {",
            "  width: 235,",
            "  margin: 5",
            "}",
            "",
            "class CheckUserAge extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    // change code below this line",
            "",
            "    // change code above this line",
            "    this.submit = this.submit.bind(this);",
            "    this.handleChange = this.handleChange.bind(this);",
            "  }",
            "  handleChange(e) {",
            "    this.setState({",
            "      input: e.target.value,",
            "      userAge: ''",
            "    });",
            "  }",
            "  submit() {",
            "    this.setState({",
            "      userAge: this.state.input",
            "    });",
            "  }",
            "  render() {",
            "    const buttonOne = <button onClick={this.submit}>Submit</button>;",
            "    const buttonTwo = <button>You May Enter</button>;",
            "    const buttonThree = <button>You Shall Not Pass</button>;",
            "    return (",
            "      <div>",
            "        <h3>Enter Your Age to Continue</h3>",
            "        <input",
            "          style={inputStyle}",
            "          type=\"number\"",
            "          value={this.state.input}",
            "          onChange={this.handleChange} /><br />",
            "        {",
            "          /* change code here */",
            "        }",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<CheckUserAge />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert(Enzyme.mount(React.createElement(CheckUserAge)).find('div').find('input').length === 1 && Enzyme.mount(React.createElement(CheckUserAge)).find('div').find('button').length === 1, 'message: The <code>CheckUserAge</code> component should render with a single <code>input</code> element and a single <code>button</code> element.');",
        "assert(Enzyme.mount(React.createElement(CheckUserAge)).state().input === '' && Enzyme.mount(React.createElement(CheckUserAge)).state().userAge === '', 'message: The <code>CheckUserAge</code> component&apos;s state should be initialized with a property of <code>userAge</code> and a property of <code>input</code>, both set to a value of an empty string.');",
        "assert(Enzyme.mount(React.createElement(CheckUserAge)).find('button').text() === 'Submit', 'message: When the <code>CheckUserAge</code> component is first rendered to the DOM, the <code>button</code>&apos;s inner text should be Submit.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(CheckUserAge)); const initialButton = mockedComponent.find('button').text(); const enter3AndClickButton = () => { mockedComponent.find('input').simulate('change', {target: { value: '3' }}); mockedComponent.find('button').simulate('click'); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find('button').text(); }); }; const enter17AndClickButton = () => { mockedComponent.find('input').simulate('change', {target: { value: '17' }}); mockedComponent.find('button').simulate('click'); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find('button').text(); }); }; const userAge3 = await enter3AndClickButton(); const userAge17 = await enter17AndClickButton(); assert(initialButton === 'Submit' && userAge3 === 'You Shall Not Pass' && userAge17 === 'You Shall Not Pass', 'message: When a number of less than 18 is entered into the <code>input</code> element and the <code>button</code> is clicked, the <code>button</code>&apos;s inner text should read <code>You Shall Not Pass</code>.'); }; ",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(CheckUserAge)); const initialButton = mockedComponent.find('button').text(); const enter18AndClickButton = () => { mockedComponent.find('input').simulate('change', {target: { value: '18' }}); mockedComponent.find('button').simulate('click'); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find('button').text(); }); }; const enter35AndClickButton = () => { mockedComponent.find('input').simulate('change', {target: { value: '35' }}); mockedComponent.find('button').simulate('click'); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find('button').text(); }); }; const userAge18 = await enter18AndClickButton(); const userAge35 = await enter35AndClickButton(); assert(initialButton === 'Submit' && userAge18 === 'You May Enter' && userAge35 === 'You May Enter', 'message: When a number greater than or equal to 18 is entered into the <code>input</code> element and the <code>button</code> is clicked, the <code>button</code>&apos;s inner text should read <code>You May Enter</code>.'); }; ",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(CheckUserAge)); const enter18AndClickButton = () => { mockedComponent.find('input').simulate('change', {target: { value: '18' }}); mockedComponent.find('button').simulate('click'); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find('button').text(); }); }; const changeInputDontClickButton = () => { mockedComponent.find('input').simulate('change', {target: { value: '5' }}); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find('button').text(); }); }; const enter10AndClickButton = () => { mockedComponent.find('input').simulate('change', {target: { value: '10' }}); mockedComponent.find('button').simulate('click'); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find('button').text(); }); }; const userAge18 = await enter18AndClickButton(); const changeInput1 = await changeInputDontClickButton(); const userAge10 = await enter10AndClickButton(); const changeInput2 = await changeInputDontClickButton(); assert(userAge18 === 'You May Enter' && changeInput1 === 'Submit' && userAge10 === 'You Shall Not Pass' && changeInput2 === 'Submit', 'message: Once a number has been submitted, and the value of the <code>input</code> is once again changed, the <code>button</code> should return to reading <code>Submit</code>.'); }; ",
        "assert(new RegExp(/(\\s|;)if(\\s|\\()/).test(Enzyme.mount(React.createElement(CheckUserAge)).instance().render.toString()) === false, 'message: Your code should not contain any <code>if/else</code> statements.');"
      ],
      "solutions": [
        "\nconst inputStyle = {\n  width: 235,\n  margin: 5\n}\n\nclass CheckUserAge extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      userAge: '',\n      input: ''\n    }\n    this.submit = this.submit.bind(this);\n    this.handleChange = this.handleChange.bind(this);\n  }\n  handleChange(e) {\n    this.setState({\n      input: e.target.value,\n      userAge: ''\n    });\n  }\n  submit() {\n    this.setState({\n      userAge: this.state.input\n    });\n  }\n  render() {\n    const buttonOne = <button onClick={this.submit}>Submit</button>;\n    const buttonTwo = <button>You May Enter</button>;\n    const buttonThree = <button>You Shall Not Pass</button>;\n    return (\n      <div>\n        <h3>Enter Your Age to Continue</h3>\n        <input\n          style={inputStyle}\n          type=\"number\"\n          value={this.state.input}\n          onChange={this.handleChange} /><br />\n          {\n            this.state.userAge === '' ?\n            buttonOne :\n            this.state.userAge >= 18 ?\n            buttonTwo :\n            buttonThree\n          }\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036188",
      "title": "Render Conditionally from Props",
      "releasedOn": "December 25, 2017",
      "description": [
        "So far, you've seen how to use <code>if/else</code>, <code>&&,</code> <code>null</code> and the ternary operator (<code>condition ? expressionIfTrue : expressionIfFalse</code>) to make conditional decisions about what to render and when. However, there's one important topic left to discuss that lets you combine any or all of these concepts with another powerful React feature: props. Using props to conditionally render code is very common with React developers &mdash; that is, they use the value of a given prop to automatically make decisions about what to render.",
        "In this challenge, you'll set up a child component to make rendering decisions based on props. You'll also use the ternary operator, but you can see how several of the other concepts that were covered in the last few challenges might be just as useful in this context.",
        "<hr>",
        "The code editor has two components that are partially defined for you: a parent called <code>GameOfChance</code>, and a child called <code>Results</code>. They are used to create a simple game where the user presses a button to see if they win or lose.",
        "First, you'll need a simple expression that randomly returns a different value every time it is run. You can use <code>Math.random()</code>. This method returns a value between <code>0</code> (inclusive) and <code>1</code> (exclusive) each time it is called. So for 50/50 odds, use <code>Math.random() > .5</code> in your expression. Statistically speaking, this expression will return <code>true</code> 50% of the time, and <code>false</code> the other 50%. On line 30, replace the comment with this expression to complete the variable declaration.",
        "Now you have an expression that you can use to make a randomized decision in the code. Next you need to implement this. Render the <code>Results</code> component as a child of <code>GameOfChance</code>, and pass in <code>expression</code> as a prop called <code>fiftyFifty</code>. In the <code>Results</code> component, write a ternary expression to render the text <code>\"You win!\"</code> or <code>\"You lose!\"</code> based on the <code>fiftyFifty</code> prop that's being passed in from <code>GameOfChance</code>. Finally, make sure the <code>handleClick()</code> method is correctly counting each turn so the user knows how many times they've played. This also serves to let the user know the component has actually updated in case they win or lose twice in a row."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class Results extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "  }",
            "  render() {",
            "    return (",
            "      <h1>",
            "      {",
            "        /* change code here */",
            "      }",
            "      </h1>",
            "    )",
            "  };",
            "};",
            "",
            "class GameOfChance extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      counter: 1",
            "    }",
            "    this.handleClick = this.handleClick.bind(this);",
            "  }",
            "  handleClick() {",
            "    this.setState({",
            "      counter: 0 // change code here",
            "    });",
            "  }",
            "  render() {",
            "    let expression = null; // change code here",
            "    return (",
            "      <div>",
            "        <button onClick={this.handleClick}>Play Again</button>",
            "        { /* change code below this line */ }",
            "",
            "        { /* change code above this line */ }",
            "        <p>{'Turn: ' + this.state.counter}</p>",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<GameOfChance />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert.strictEqual(Enzyme.mount(React.createElement(GameOfChance)).find('GameOfChance').length, 1, 'message: The <code>GameOfChance</code> component should exist and render to the page.');",
        "assert.strictEqual(Enzyme.mount(React.createElement(GameOfChance)).find('button').length, 1, 'message: <code>GameOfChance</code> should return a single <code>button</code> element.');",
        "assert(Enzyme.mount(React.createElement(GameOfChance)).find('Results').length === 1 && Enzyme.mount(React.createElement(GameOfChance)).find('Results').props().hasOwnProperty('fiftyFifty') === true, 'message: <code>GameOfChance</code> should return a single instance of the <code>Results</code> component, which has a prop called <code>fiftyFifty</code>.');",
        "assert.strictEqual(Enzyme.mount(React.createElement(GameOfChance)).state().counter, 1, 'message: <code>GameOfChance</code> state should be initialized with a property of <code>counter</code> set to a value of <code>1</code>.');",
        "assert.strictEqual(Enzyme.mount(React.createElement(GameOfChance)).find('p').text(), 'Turn: 1', 'message: When the <code>GameOfChance</code> component is first rendered to the DOM, a <code>p</code> element should be returned with the inner text of <code>Turn: 1</code>.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const comp = Enzyme.mount(React.createElement(GameOfChance)); const simulate = () => { comp.find('button').simulate('click'); };const result = () => ({ count: comp.state('counter'), text: comp.find('p').text() });const _1 = () => { simulate(); return waitForIt(() => result())}; const _2 = () => { simulate(); return waitForIt(() => result())}; const _3 = () => { simulate(); return waitForIt(() => result())}; const _4 = () => { simulate(); return waitForIt(() => result())}; const _5 = () => { simulate(); return waitForIt(() => result())}; const _1_val = await _1(); const _2_val = await _2(); const _3_val = await _3(); const _4_val = await _4(); const _5_val = await _5(); assert(_1_val.count === 2 && _1_val.text === 'Turn: 2' && _2_val.count === 3 && _2_val.text === 'Turn: 3' && _3_val.count === 4 && _3_val.text === 'Turn: 4' && _4_val.count === 5 && _4_val.text === 'Turn: 5' && _5_val.count === 6 && _5_val.text === 'Turn: 6', 'message: Each time the button is clicked, the counter state should be incremented by a value of 1, and a single <code>p</code> element should be rendered to the DOM that contains the text \"Turn: N\", where N is the value of the counter state.'); }; ",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const comp = Enzyme.mount(React.createElement(GameOfChance)); const simulate = () => { comp.find('button').simulate('click'); };const result = () => ({ h1: comp.find('h1').length, text: comp.find('h1').text() });const _1 = result(); const _2 = () => { simulate(); return waitForIt(() => result())}; const _3 = () => { simulate(); return waitForIt(() => result())}; const _4 = () => { simulate(); return waitForIt(() => result())}; const _5 = () => { simulate(); return waitForIt(() => result())}; const _6 = () => { simulate(); return waitForIt(() => result())}; const _7 = () => { simulate(); return waitForIt(() => result())}; const _8 = () => { simulate(); return waitForIt(() => result())}; const _9 = () => { simulate(); return waitForIt(() => result())}; const _10 = () => { simulate(); return waitForIt(() => result())}; const _2_val = await _2(); const _3_val = await _3(); const _4_val = await _4(); const _5_val = await _5(); const _6_val = await _6(); const _7_val = await _7(); const _8_val = await _8(); const _9_val = await _9(); const _10_val = await _10(); const __text = new Set([_1.text, _2_val.text, _3_val.text, _4_val.text, _5_val.text, _6_val.text, _7_val.text, _8_val.text, _9_val.text, _10_val.text]); const __h1 = new Set([_1.h1, _2_val.h1, _3_val.h1, _4_val.h1, _5_val.h1, _6_val.h1, _7_val.h1, _8_val.h1, _9_val.h1, _10_val.h1]); assert(__text.size === 2 && __h1.size === 1, 'message: When the <code>GameOfChance</code> component is first mounted to the DOM and each time the button is clicked thereafter, a single <code>h1</code> element should be returned that randomly renders either <code>You Win!</code> or <code>You Lose!</code>.'); }; "
      ],
      "solutions": [
        "class Results extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n  render() {\n    return (\n      <h1>\n      {\n        this.props.fiftyFifty ?\n        'You Win!' :\n        'You Lose!'\n      }\n      </h1>\n    )\n  };\n};\n\nclass GameOfChance extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      counter: 1\n    }\n    this.handleClick = this.handleClick.bind(this);\n  }\n  handleClick() {\n    this.setState({\n      counter: this.state.counter + 1\n    });\n  }\n  render() {\n    const expression = Math.random() > .5;\n    return (\n      <div>\n        <button onClick={this.handleClick}>Play Again</button>\n        <Results fiftyFifty={expression} />\n        <p>{'Turn: ' + this.state.counter}</p>\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d4036189",
      "title": "Change Inline CSS Conditionally Based on Component State",
      "releasedOn": "December 25, 2017",
      "description": [
        "At this point, you've seen several applications of conditional rendering and the use of inline styles. Here's one more example that combines both of these topics. You can also render CSS conditionally based on the state of a React component. To do this, you check for a condition, and if that condition is met, you modify the styles object that's assigned to the JSX elements in the render method.",
        "This paradigm is important to understand because it is a dramatic shift from the more traditional approach of applying styles by modifying DOM elements directly (which is very common with jQuery, for example). In that approach, you must keep track of when elements change and also handle the actual manipulation directly. It can become difficult to keep track of changes, potentially making your UI unpredictable. When you set a style object based on a condition, you describe how the UI should look as a function of the application's state. There is a clear flow of information that only moves in one direction. This is the preferred method when writing applications with React.",
        "<hr>",
        "The code editor has a simple controlled input component with a styled border. You want to style this border red if the user types more than 15 characters of text in the input box. Add a condition to check for this and, if the condition is valid, set the input border style to <code>3px solid red</code>. You can try it out by entering text in the input."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "",
            "class GateKeeper extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      input: ''",
            "    };",
            "    this.handleChange = this.handleChange.bind(this);",
            "  }",
            "  handleChange(event) {",
            "    this.setState({ input: event.target.value })",
            "  }",
            "  render() {",
            "    let inputStyle = {",
            "      border: '1px solid black'",
            "    };",
            "    // change code below this line",
            "",
            "    // change code above this line",
            "    return (",
            "      <div>",
            "        <h3>Don't Type Too Much:</h3>",
            "        <input",
            "          type=\"text\"",
            "          style={inputStyle}",
            "          value={this.state.input}",
            "          onChange={this.handleChange} />",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<GateKeeper />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(GateKeeper)); return mockedComponent.find('div').length === 1; })(), 'message: The <code>GateKeeper</code> component should render a <code>div</code> element.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(GateKeeper)); return mockedComponent.state().input === ''; })(), 'message: The <code>GateKeeper</code> component should be initialized with a state key <code>input</code> set to an empty string.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(GateKeeper)); return mockedComponent.find('h3').length === 1 && mockedComponent.find('input').length === 1; })(), 'message: The <code>GateKeeper</code> component should render an <code>h3</code> tag and an <code>input</code> tag.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(GateKeeper)); return mockedComponent.find('input').props().style.border === '1px solid black'; })(), 'message: The <code>input</code> tag should initially have a style of <code>1px solid black</code> for the <code>border</code> property.');",
        "async () => {  const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const mockedComponent = Enzyme.mount(React.createElement(GateKeeper)); const simulateChange = (el, value) => el.simulate('change', {target: {value}}); let initialStyle = mockedComponent.find('input').props().style.border; const state_1 = () => { mockedComponent.setState({input: 'this is 15 char' }); return waitForIt(() => mockedComponent.find('input').props().style.border )}; const state_2 = () => { mockedComponent.setState({input: 'A very long string longer than 15 characters.' }); return waitForIt(() => mockedComponent.find('input').props().style.border )}; const style_1 = await state_1(); const style_2 = await state_2(); assert(initialStyle === '1px solid black' && style_1 === '1px solid black' && style_2 === '3px solid red', 'message: The <code>input</code> tag should be styled with a border of <code>3px solid red</code> if the input value in state is longer than 15 characters.'); }; "
      ],
      "solutions": [
        "\nclass GateKeeper extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      input: ''\n    };\n    this.handleChange = this.handleChange.bind(this);\n  }\n  handleChange(event) {\n    this.setState({ input: event.target.value })\n  }\n  render() {\n    let inputStyle = {\n      border: '1px solid black'\n    };\n    if (this.state.input.length > 15) {\n      inputStyle.border = '3px solid red';\n    };\n    return (\n      <div>\n        <h3>Don't Type Too Much:</h3>\n        <input\n          type=\"text\"\n          style={inputStyle}\n          value={this.state.input}\n          onChange={this.handleChange} />\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d403618a",
      "title": "Use Array.map() to Dynamically Render Elements",
      "releasedOn": "December 25, 2017",
      "description": [
        "Conditional rendering is useful, but you may need your components to render an unknown number of elements. Often in reactive programming, a programmer has no way to know what the state of an application is until runtime, because so much depends on a user's interaction with that program. Programmers need to write their code to correctly handle that unknown state ahead of time. Using <code>Array.map()</code> in React illustrates this concept.",
        "For example, you create a simple \"To Do List\" app. As the programmer, you have no way of knowing how many items a user might have on their list. You need to set up your component to <em><strong>dynamically render</strong></em> the correct number of list elements long before someone using the program decides that today is laundry day. ",
        "<hr>",
        "The code editor has most of the <code>MyToDoList</code> component set up. Some of this code should look familiar if you completed the controlled form challenge. You'll notice a <code>textarea</code> and a <code>button</code>, along with a couple of methods that track their states, but nothing is rendered to the page yet.",
        "Inside the <code>constructor</code>, create a <code>this.state</code> object and define two states: <code>userInput</code> should be initialized as an empty string, and <code>toDoList</code> should be initialized as an empty array. Next, delete the comment in the <code>render()</code> method next to the <code>items</code> variable. In its place, map over the <code>toDoList</code> array stored in the component's internal state and dynamically render a <code>li</code> for each item. Try entering the string <code>eat, code, sleep, repeat</code> into the <code>textarea</code>, then click the button and see what happens.",
        "<strong>Note:</strong>&nbsp;You may know that all sibling child elements created by a mapping operation like this do need to be supplied with a unique <code>key</code> attribute. Don't worry, this is the topic of the next challenge."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "const textAreaStyles = {",
            "  width: 235,",
            "  margin: 5",
            "};",
            "",
            "class MyToDoList extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    // change code below this line",
            "",
            "    // change code above this line",
            "    this.handleSubmit = this.handleSubmit.bind(this);",
            "    this.handleChange = this.handleChange.bind(this);",
            "  }",
            "  handleSubmit() {",
            "    const itemsArray = this.state.userInput.split(',');",
            "    this.setState({",
            "      toDoList: itemsArray",
            "    });",
            "  }",
            "  handleChange(e) {",
            "    this.setState({",
            "      userInput: e.target.value",
            "    });",
            "  }",
            "  render() {",
            "    const items = null; // change code here",
            "    return (",
            "      <div>",
            "        <textarea",
            "          onChange={this.handleChange}",
            "          value={this.state.userInput}",
            "          style={textAreaStyles}",
            "          placeholder=\"Separate Items With Commas\" /><br />",
            "        <button onClick={this.handleSubmit}>Create List</button>",
            "        <h1>My \"To Do\" List:</h1>",
            "        <ul>",
            "          {items}",
            "        </ul>",
            "      </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<MyToDoList />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); return mockedComponent.find('MyToDoList').length === 1; })(), 'message: The MyToDoList component should exist and render to the page.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); return mockedComponent.find('MyToDoList').children().childAt(0).type() === 'textarea'; })(), 'message: The first child of <code>MyToDoList</code> should be a <code>textarea</code> element.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); return mockedComponent.find('MyToDoList').children().childAt(2).type() === 'button'; })(), 'message: The third child of <code>MyToDoList</code> should be a <code>button</code> element.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); const initialState = mockedComponent.state(); return Array.isArray(initialState.toDoList) === true && initialState.toDoList.length === 0; })(), 'message: The state of <code>MyToDoList</code> should be initialized with <code>toDoList</code> as an empty array.');",
        "assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); const initialState = mockedComponent.state(); return typeof initialState.userInput === 'string' && initialState.userInput.length === 0; })(), 'message: The state of <code>MyToDoList</code> should be initialized with <code>userInput</code> as an empty string.');",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); const simulateChange = (el, value) => el.simulate('change', {target: {value}}); const state_1 = () => { return waitForIt(() => mockedComponent.find('ul').find('li'))}; const setInput = () => { return waitForIt(() => simulateChange(mockedComponent.find('textarea'), \"testA, testB, testC\"))}; const click = () => { return waitForIt(() => mockedComponent.find('button').simulate('click'))}; const state_2 = () => { return waitForIt(() => { const nodes = mockedComponent.find('ul').find('li'); return { nodes, text: nodes.reduce((t, n) => t + n.text(), '') }; })}; const setInput_2 = () => { return waitForIt(() => simulateChange(mockedComponent.find('textarea'), \"t1, t2, t3, t4, t5, t6\"))}; const click_1 = () => { return waitForIt(() => mockedComponent.find('button').simulate('click'))}; const state_3 = () => { return waitForIt(() => { const nodes = mockedComponent.find('ul').find('li'); return { nodes, text: nodes.reduce((t, n) => t + n.text(), '') }; })}; const awaited_state_1 = await state_1(); const awaited_setInput = await setInput(); const awaited_click = await click(); const awaited_state_2 = await state_2(); const awaited_setInput_2 = await setInput_2(); const awaited_click_1 = await click_1(); const awaited_state_3 = await state_3(); assert(awaited_state_1.length === 0 && awaited_state_2.nodes.length === 3 && awaited_state_3.nodes.length === 6 && awaited_state_2.text === 'testA testB testC' && awaited_state_3.text === 't1 t2 t3 t4 t5 t6', 'message: When the <code>Create List</code> button is clicked, the <code>MyToDoList</code> component should dynamically return an unordered list that contains a list item element for every item of a comma-separated list entered into the <code>textarea</code> element.'); }; "
      ],
      "solutions": [
        "\nconst textAreaStyles = {\n  width: 235,\n  margin: 5\n};\n\nclass MyToDoList extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      toDoList: [],\n      userInput: ''\n    }\n    this.handleSubmit = this.handleSubmit.bind(this);\n    this.handleChange = this.handleChange.bind(this);\n  }\n  handleSubmit() {\n    const itemsArray = this.state.userInput.split(',');\n    this.setState({\n      toDoList: itemsArray\n    });\n  }\n  handleChange(e) {\n    this.setState({\n      userInput: e.target.value\n    });\n  }\n  render() {\n    const items = this.state.toDoList.map( (item, i) => {\n      return <li key={i}>{item}</li>\n    });\n    return (\n      <div>\n        <textarea\n          onChange={this.handleChange}\n          value={this.state.userInput}\n          style={textAreaStyles}\n          placeholder=\"Separate Items With Commas\" /><br />\n        <button onClick={this.handleSubmit}>Create List</button>\n        <h1>My \"To Do\" List:</h1>\n        <ul>\n          {items}\n        </ul>\n      </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d403618b",
      "title": "Give Sibling Elements a Unique Key Attribute",
      "releasedOn": "December 25, 2017",
      "description": [
        "The last challenge showed how the <code>map</code> method is used to dynamically render a number of elements based on user input. However, there was an important piece missing from that example. When you create an array of elements, each one needs a <code>key</code> attribute set to a unique value. React uses these keys to keep track of which items are added, changed, or removed. This helps make the re-rendering process more efficient when the list is modified in any way. Note that keys only need to be unique between sibling elements, they don't need to be globally unique in your application.",
        "<hr>",
        "The code editor has an array with some front end frameworks and a stateless functional component named <code>Frameworks()</code>. <code>Frameworks()</code> needs to map the array to an unordered list, much like in the last challenge. Finish writing the <code>map</code> callback to return an <code>li</code> element for each framework in the <code>frontEndFrameworks</code> array. This time, make sure to give each <code>li</code> a <code>key</code> attribute, set to a unique value.",
        "Normally, you want to make the key something that uniquely identifies the element being rendered. As a last resort the array index may be used, but typically you should try to use a unique identification."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "",
            "const frontEndFrameworks = [",
            "  'React',",
            "  'Angular',",
            "  'Ember',",
            "  'Knockout',",
            "  'Backbone',",
            "  'Vue'",
            "];",
            "",
            "function Frameworks() {",
            "  const renderFrameworks = null; // change code here",
            "  return (",
            "    <div>",
            "      <h1>Popular Front End JavaScript Frameworks</h1>",
            "      <ul>",
            "        {renderFrameworks}",
            "      </ul>",
            "    </div>",
            "  );",
            "};"
          ],
          "tail": "ReactDOM.render(<Frameworks />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert(Enzyme.mount(React.createElement(Frameworks)).find('Frameworks').length === 1, 'message: The <code>Frameworks</code> component should exist and render to the page.');",
        "assert(Enzyme.mount(React.createElement(Frameworks)).find('h1').length === 1, 'message: <code>Frameworks</code> should render an <code>h1</code> element.');",
        "assert(Enzyme.mount(React.createElement(Frameworks)).find('ul').length === 1, 'message: <code>Frameworks</code> should render a <code>ul</code> element.');",
        "assert(Enzyme.mount(React.createElement(Frameworks)).find('ul').children().length === 6 && Enzyme.mount(React.createElement(Frameworks)).find('ul').childAt(0).name() === 'li' && Enzyme.mount(React.createElement(Frameworks)).find('li').length === 6, 'message: The <code>ul</code> tag should render 6 child <code>li</code> elements.');",
        "assert((() => { const ul = Enzyme.mount(React.createElement(Frameworks)).find('ul'); const keys = new Set([ ul.childAt(0).key(), ul.childAt(1).key(), ul.childAt(2).key(), ul.childAt(3).key(), ul.childAt(4).key(), ul.childAt(5).key(), ]); return keys.size === 6; })(), 'message: Each list item element should have a unique <code>key</code> attribute.');"
      ],
      "solutions": [
        "\nconst frontEndFrameworks = [\n  'React',\n  'Angular',\n  'Ember',\n  'Knockout',\n  'Backbone',\n  'Vue'\n];\n\nfunction Frameworks() {\n  const renderFrameworks = frontEndFrameworks.map((fw, i) => {\n    return <li key={i}>{fw}</li>\n  })\n  return (\n    <div>\n      <h1>Popular Front End JavaScript Frameworks</h1>\n      <ul>\n        {renderFrameworks}\n      </ul>\n    </div>\n  );\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d403618c",
      "title": "Use Array.filter() to Dynamically Filter an Array",
      "releasedOn": "December 25, 2017",
      "description": [
        "The <code>map</code> array method is a powerful tool that you will use often when working with React. Another method related to <code>map</code> is <code>filter</code>, which filters the contents of an array based on a condition, then returns a new array. For example, if you have an array of users that all have a property <code>online</code> which can be set to <code>true</code> or <code>false</code>, you can filter only those users that are online by writing:",
        "<code>let onlineUsers = users.filter(user => user.online);</code>",
        "<hr>",
        "In the code editor, <code>MyComponent</code>&apos;s <code>state</code> is initialized with an array of users. Some users are online and some aren't. Filter the array so you see only the users who are online. To do this, first use <code>filter</code> to return a new array containing only the users whose <code>online</code> property is <code>true</code>. Then, in the <code>renderOnline</code> variable, map over the filtered array, and return a <code>li</code> element for each user that contains the text of their <code>username</code>. Be sure to include a unique <code>key</code> as well, like in the last challenges."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "contents": [
            "class MyComponent extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "    this.state = {",
            "      users: [",
            "        {",
            "          username: 'Jeff',",
            "          online: true",
            "        },",
            "        {",
            "          username: 'Alan',",
            "          online: false",
            "        },",
            "        {",
            "          username: 'Mary',",
            "          online: true",
            "        },",
            "        {",
            "          username: 'Jim',",
            "          online: false",
            "        },",
            "        {",
            "          username: 'Sara',",
            "          online: true",
            "        },",
            "        {",
            "          username: 'Laura',",
            "          online: true",
            "        }",
            "      ]",
            "    }",
            "  }",
            "  render() {",
            "    const usersOnline = null; // change code here",
            "    const renderOnline = null; // change code here",
            "    return (",
            "       <div>",
            "         <h1>Current Online Users:</h1>",
            "         <ul>",
            "           {renderOnline}",
            "         </ul>",
            "       </div>",
            "    );",
            "  }",
            "};"
          ],
          "tail": "ReactDOM.render(<MyComponent />, document.getElementById('root'))"
        }
      },
      "tests": [
        "assert.strictEqual(Enzyme.mount(React.createElement(MyComponent)).find('MyComponent').length, 1, 'message: <code>MyComponent</code> should exist and render to the page.');",
        "assert(Array.isArray(Enzyme.mount(React.createElement(MyComponent)).state('users')) === true && Enzyme.mount(React.createElement(MyComponent)).state('users').length === 6, \"message: <code>MyComponent</code>&apos;s state should be initialized to an array of six users.\");",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const comp = Enzyme.mount(React.createElement(MyComponent)); const users = (bool) => ({users:[ { username: 'Jeff', online: bool }, { username: 'Alan', online: bool }, { username: 'Mary', online: bool }, { username: 'Jim', online: bool   }, { username: 'Laura', online: bool } ]}); const result = () => comp.find('li').length; const _1 = result(); const _2 = () => { comp.setState(users(true)); return waitForIt(() => result()) }; const _3 = () => { comp.setState(users(false)); return waitForIt(() => result()) }; const _4 = () => { comp.setState({ users: [] }); return waitForIt(() => result()) }; const _2_val = await _2(); const _3_val = await _3(); const _4_val = await _4(); assert(comp.find('div').length === 1 && comp.find('h1').length === 1 && comp.find('ul').length === 1 && _1 === 4 && _2_val === 5 && _3_val === 0 && _4_val === 0, 'message: <code>MyComponent</code> should return a <code>div</code>, an <code>h1</code>, and then an unordered list containing <code>li</code> elements for every user whose online status is set to <code>true</code>.'); }; ",
        "async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const comp = Enzyme.mount(React.createElement(MyComponent)); const users = (bool) => ({users:[ { username: 'Jeff', online: bool }, { username: 'Alan', online: bool }, { username: 'Mary', online: bool }, { username: 'Jim', online: bool   }, { username: 'Laura', online: bool } ]}); const ul = () => { comp.setState(users(true)); return waitForIt(() => comp.find('ul').html()) }; const html = await ul(); assert(html === '<ul><li>Jeff</li><li>Alan</li><li>Mary</li><li>Jim</li><li>Laura</li></ul>', 'message: <code>MyComponent</code> should render <code>li</code> elements that contain the username of each online user.'); }; ",
        "assert((() => { const ul = Enzyme.mount(React.createElement(MyComponent)).find('ul'); console.log(ul.debug()); const keys = new Set([ ul.childAt(0).key(), ul.childAt(1).key(), ul.childAt(2).key(), ul.childAt(3).key() ]); return keys.size === 4; })(), 'message: Each list item element should have a unique <code>key</code> attribute.');"
      ],
      "solutions": [
        "\nclass MyComponent extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      users: [\n        {\n          username: 'Jeff',\n          online: true\n        },\n        {\n          username: 'Alan',\n          online: false\n        },\n        {\n          username: 'Mary',\n          online: true\n        },\n        {\n          username: 'Jim',\n          online: false\n        },\n        {\n          username: 'Sara',\n          online: true\n        },\n        {\n          username: 'Laura',\n          online: true\n        }\n      ]\n    }\n  }\n  render() {\n    const usersOnline = this.state.users.filter(user => {\n      return user.online;\n    });\n    const renderOnlineUsers = usersOnline.map(user => {\n      return (\n        <li key={user.username}>{user.username}</li>\n      );\n    });\n    return (\n       <div>\n         <h1>Current Online Users:</h1>\n         <ul>\n          {renderOnlineUsers}\n        </ul>\n       </div>\n    );\n  }\n};"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    },
    {
      "id": "5a24c314108439a4d403618d",
      "title": "Render React on the Server with renderToString",
      "releasedOn": "December 25, 2017",
      "description": [
        "So far, you have been rendering React components on the client. Normally, this is what you will always do. However, there are some use cases where it makes sense to render a React component on the server. Since React is a JavaScript view library and you can run JavaScript on the server with Node, this is possible. In fact, React provides a <code>renderToString()</code> method you can use for this purpose.",
        "There are two key reasons why rendering on the server may be used in a real world app. First, without doing this, your React apps would consist of a relatively empty HTML file and a large bundle of JavaScript when it's initially loaded to the browser. This may not be ideal for search engines that are trying to index the content of your pages so people can find you. If you render the initial HTML markup on the server and send this to the client, the initial page load contains all of the page's markup which can be crawled by search engines. Second, this creates a faster initial page load experience because the rendered HTML is smaller than the JavaScript code of the entire app. React will still be able to recognize your app and manage it after the initial load.",
        "<hr>",
        "The <code>renderToString()</code> method is provided on <code>ReactDOMServer</code>, which is available here as a global object. The method takes one argument which is a React element. Use this to render <code>App</code> to a string."
      ],
      "files": {
        "indexjsx": {
          "key": "indexjsx",
          "ext": "jsx",
          "name": "index",
          "head": [
            "var ReactDOMServer = { renderToString(x) { return null; } };"
          ],
          "contents": [
            "",
            "class App extends React.Component {",
            "  constructor(props) {",
            "    super(props);",
            "  }",
            "  render() {",
            "    return <div/>",
            "  }",
            "};",
            "",
            "// change code below this line",
            ""
          ],
          "tail": "ReactDOM.render(<App />, document.getElementById('root'))"
        }
      },
      "tests": [
        "getUserInput => assert(getUserInput('index').replace(/ /g,'').includes('ReactDOMServer.renderToString(<App/>)') && Enzyme.mount(React.createElement(App)).children().name() === 'div', 'message: The <code>App</code> component should render to a string using <code>ReactDOMServer.renderToString</code>.');"
      ],
      "solutions": [
        "\nclass App extends React.Component {\n  constructor(props) {\n    super(props);\n  }\n  render() {\n    return <div/>\n  }\n};\n\n// change code below this line\nReactDOMServer.renderToString(<App/>);"
      ],
      "type": "modern",
      "isRequired": false,
      "translations": {},
      "react": true
    }
  ]
}
