React Components, State and Props
Components
A React application usually consists of several dynamic React components combined together, where each component has a separation of concerns & child components are nested within parent components.
We Declare a new class that extends React’s Component class, which provides us with built in methods & attributes.
class <ComponentName> extends Component {
render() {
return ( //Your Code Goes Here ) }
}
React components must explicitly return 1 & only 1 JSX storage element within their render() method.
The JSX storage element contains all our remaining code.
Once a component is defined, we invoke it in it’s parent components’ render() method via
Syntax: <ComponentName />
We can write additional code (i.e. define methods) inside the Component‘s scope & outside of the render() method.
- Methods defined here must be prepended with the keyword “this” when invoked in other parts of our code via
{ this.functionName() } || { this.functionName} in an event
- Use arrow functions so these methods are implicitly bound to their class of origin
Props
We can pass units of information from a parent component down to a child component using props.
- Think of props as space-separated attributes of JSX child components
Syntax: < ChildComponentName propName = { propValue} />
- A prop’s value can be any data type: string, number, boolean, object, function, etc
- A prop’s value is accessible within the ChildComponentClass via
Syntax: { this.props.propName }
We use default props for a component if a specific propValue is not provided / is undefined.
- We define default props outside of the component class
ComponentClassName.defaultProps = { propName: defaultPropValue }
State
A components state property is data that’s expected to change during the components life & is visible in the UI.
We initialize the state object in the constructor() method:
constructor() {
super()
this.state = { stateKey: stateInitialValue }
}
We must call super() in the constructor as we are inheriting from the React’s Component class.
We call the state in the components’ render() method via
Syntax: { this.state.stateKey }
Updating State
We update the state of our components using this.setState(), an asynchronous method that’s provided by React’s Component class.
- Define the change you want to make to the stateValue
- Update the state object
Syntax: this.setState( { stateKey : stateNewValue } )
The component will then re-render, because its state has changed & its UI will be updated.
this.setState(objectRepresentingTheChange, callbackFcn)
When updating the state object, we just change the key-value property we want to update, React will merge the new state with the existing state.
Now that you have a basic idea of the moving parts of a React app, Happy Coding !