Lecture 4
Lecture 4
React Components
Components are like functions that return HTML elements.
Components are independent and reusable bits of code. They serve the
same purpose as JavaScript functions, but work in isolation and return
HTML.
In older React code bases, you may find Class components primarily used. It
is now suggested to use Function components along with Hooks, which were
added in React 16.8. There is an optional section on Class components for
your reference.
Class Component
The component also requires a render() method, this method returns HTML.
Example
render() {
}
Lecture 4
Function Component
A Function component also returns HTML, and behaves much the same way
as a Class component, but Function components can be written using much
less code, are easier to understand.
Example
function Car() {
Rendering a Component
Now your React application has a component called Car, which returns
an <h2> element.
Example
Display the Car component in the "root" element:
root.render(<Car />);
Props
Components can be passed as props, which stands for properties.
Props are like function arguments, and you send them into the component as
attributes.
Lecture 4
Example
Use an attribute to pass a color to the Car component, and use it in the render()
function:
function Car(props) {
root.render(<Car color="red"/>);