React Component
A component is a small, reusable chuck of code that is responsible for one job (often is to render some HTML)
The purpose of React is to create multiple files containing UI code and import it into one single file to render in index.html
Use <MyComponentClass />
to render a React component. This is called a Component Instance
Create a Component Class
Every component must have a component class (like a factory to create components)
React.Component
is a class for JavaScript therefore, we need to add subclass class MyComponent extends React.Component {}
Component class name needs to be a capital letters!
What goes inside { }
- The Render Function
class MyComponent extends React.Component{
render(){
}
}
2. Return Statement
A render method must contain a return
statement (usually returns a JSX expression).
class MyComponent extends React.Component{
render(){
return <h1> Hello World! </h1>;
}
}
Don’t forget
;
after return statement
Multi-Line JSX in a Component
Anything you want to
return()
has to be within one single<div>...</div>
IF statement in Component
You can include an IF statement before the return function in a Component
'This'
in a Component
this
refers to Component name. You don’t need ( ) after .food
because a getter method is used.
Event Listener in a Component
Render function will contain event listeners. In React, you can define event handlers as methods on a component class:
class MyClass extends React.Component {
myFunc() {
alert('Hello World!');
} render() {
return (
<div onHover={myFunc}>
</div>
);
}
}