React Component

Architecture

Objectives

  • Pass state to child components as props

  • Define which components own state

  • Use stateless functional components

How Is State Shared?

  • State is always passed from a parent down to a child component as a prop

  • State should not be passed to a sibling or a parent

Who owns the state?

class App extends Component {
  render() {
    return (
      <div>
       <Navbar />
       <TicTacToe />
      </div>
    );
  }
}

Owns the state

Wants State

State Should Be Owned by 1 Component

class InstructorItem extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      name: this.props.name,
      hobbies: this.props.hobbies
    };
  }
  render() {
    return (
      <div>
        <h3>{this.state.name}</h3>
        <h4>
         Hobbies: {this.state.hobbies.join(", ")}
        </h4>
      </div>
    );
  }
}

Bad Practice: Don't Do This

Stateless Functional Components

Components implemented using a function,

not a class

The function implements the render method only:

no constructor, no state

import React from 'react';

const Greeting = props => (
  <h1>Hello, {props.name}</h1>
);

export default Greeting;

Stateless Functional Component

Thinking In React

Component Architecture

By Elie Schoppik

Component Architecture

  • 3,210