React Fundamentals II
Kay Ashaolu
Components
- This is one of the things I like the most about React
- The focus on components as independent, resusable pieces that can be placed anywhere
- This uses the composability relationship: each element can be composed by other elements
Components
- Using a combination of JSX and JavaScript, you can bundle look and feel and functionality in a single JavaScript class
- You can consider these React Elements and HTML Elements that you can place wherever you like
- Let's get into the anatomy of a Component
Component Example
import React from "react";
import ReactDOM from "react-dom";
class FormatName extends React.Component {
constructor(props) {
super(props);
}
format() {
return `${this.props.firstName} ${this.props.lastName}`
}
render() {
return (
<h1>
Hello, {this.format()}!
</h1>
);
}
}
ReactDOM.render(
<FormatName firstName="Kay" lastName="Ashaolu" />,
document.getElementById('root')
);
Component Example Explained
- We are creating a JavaScript class that will represent an element
- The name of the class (i.e. FormatName) is the name of the element
- The constructor of the class is connected to the element definition you see in the ReactDOM.render line of code
Component Construtor
- constructor(props)
- The "constructor" function is executed when you want to create an instance of a class
- When you add "<FormatName />", this constructor function is called
- A parameter called props is passed into this constructor
- props is an object that contains all of the attributes and values that are passed into the element
Component Instance Properties
- When you add the attribute firstName="Kay", this props object will have a key named "firstName"
- And a value named "Kay"
- These properties are immutable
<FormatName firstName="Kay" lastName="Ashaolu" />,
Component Render function
- One of the functions that are used within React is the render() function
- The render() function is called when a component is told by the React library to render (e.g. on a call on ReactDOM.render())
- This function returns JSX code that the component would render into
Component Render function
render() {
return (
<h1>
Hello, {this.formatName()}!
</h1>
);
}
Component custom functions
- React Components are just JavaScript classes
- So you can add your own classes to your components
- In this example we added the function "format" that will format the firstName and lastname properties
Component custom functions
format() {
return `${this.props.firstName} ${this.props.lastName}`
}