Write a React Component from Scratch
Problem Explanation
In this challenge we want to create a class
react component (React components can be class
components or function
components). All of our class components are going to be an extention of React.Component
. For example we can start to make a component called FirstComponent
with:
class FirstComponent extends React.Component {}
We also need to be sure to define the constructor
for our new class. It is best practice to call any component’s constructor
with super
and to pass props
to both. super
pulls the constructor
of our component’s parent class (in this case React.Component
). Now, the code for our component looks like this:
class FirstComponent extends React.Component {
constructor(props) {
super(props);
}
}
Now all that’s left to do is define what our component will render
! We do this by calling the component’s render
method, and returning our JSX code:
class FirstComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
// The JSX code you put here is what your component will render
);
}
};
Once your JSX code is in there, your component is complete! If you want a more granular tutorial of React components Samer Buna wrote a great article.
Solutions
Solution 1 (Click to Show/Hide)
// change code below this line
class MyComponent extends React.Component{
constructor(props){
super(props);
}
render(){
return(
<div id="challenge-node">
<h1>My First React Component!</h1>
</div>
);
}
};
ReactDOM.render(<MyComponent/>, document.getElementById("challenge-node"));
Code Explanation
- Code explanation goes here