3.5 KiB
3.5 KiB
id | title | challengeType | isRequired |
---|---|---|---|
5a24c314108439a4d4036163 | Create a React Component | 6 | false |
Description
class
syntax. In the following example, Kitten
extends React.Component
:
class Kitten extends React.Component {This creates an ES6 class
constructor(props) {
super(props);
}
render() {
return (
<h1>Hi</h1>
);
}
}
Kitten
which extends the React.Component
class. So the Kitten
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 Kitten
class has a constructor
defined within it that calls super()
. It uses super()
to call the constructor of the parent class, in this case React.Component
. The constructor is a special method used during the initialization of objects that are created with the class
keyword. It is best practice to call a component's constructor
with super
, and pass props
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 props
.
Instructions
MyComponent
is defined in the code editor using class syntax. Finish writing the render
method so it returns a div
element that contains an h1
with the text Hello React!
.
Tests
tests:
- text: The React component should return a <code>div</code> element.
testString: assert(Enzyme.shallow(React.createElement(MyComponent)).type() === 'div', 'The React component should return a <code>div</code> element.');
- text: The returned <code>div</code> should render an <code>h1</code> header within it.
testString: assert(/<div><h1>.*<\/h1><\/div>/.test(Enzyme.shallow(React.createElement(MyComponent)).html()), 'The returned <code>div</code> should render an <code>h1</code> header within it.');
- text: The <code>h1</code> header should contain the string <code>Hello React!</code>.
testString: assert(Enzyme.shallow(React.createElement(MyComponent)).html() === '<div><h1>Hello React!</h1></div>', 'The <code>h1</code> header should contain the string <code>Hello React!</code>.');
Challenge Seed
class MyComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
// change code below this line
// change code above this line
}
};
After Test
ReactDOM.render(<MyComponent />, document.getElementById('root'))
Solution
class MyComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
// change code below this line
return (
<div>
<h1>Hello React!</h1>
</div>
);
// change code above this line
}
};