React components

From wikinotes
Revision as of 00:44, 15 June 2021 by Will (talk | contribs) (→‎Functions)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Component Functions

function Description(props) {
    return (
        <h1>Description</h1>
        <p>{props.paragraph}</p>
    )
}

Component Classes

class Employee extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: "vaderd", id: 101} 
  }

  render() {
    return (
      <div>
        <h1>Name: {this.state.name}</h1>
        <h2>ID: {this.state.id}</h2>
      </div>
    );
  }
}

Lifecycle Methods

React components have methods to mount/unmount behaviours when the object is first created or destroyed.
These can set/unset timers to auto-update the object.

Check out the tutorial.

TODO:

Why can't the constructor/destructor be used?

class Foo extends React.Component {
  componentDidMount() { ... }
  componentWillUnmount() { ... }
}

DOM Events

You can subscribe to DOM events with callbacks similarly to javascript.
except that events are in camelcase
and callbacks are defined as methods rather than strings.

See https://reactjs.org/docs/handling-events.html

class HelloWorld extends React.Component {
  sayHello() {
    console.log('hello')
  }

  render() {
    return (
      <button onClick={() => this.sayHello()}>
        Say Hello
      </button>
    );
  }
}

Element Variables

You can configure a component to manage it's display based on a state variable.
In this way, it fully encapsulates it's behaviour.

TODO:

untested

const Button = styled.button

class MyButton extends React.Component {
  constructor(props) {
    super(props)
    this.state = { collapsed: false }
    this.handleExpandClicked = this.handleExpandClicked.bind(this)
    this.handleCollapseClicked = this.handleCollapseClicked.bind(this)
  }
  
  handleExpandClicked() { this.setState({ collapsed: false }) }
  handleCollapseClicked() { this.setState({ collapsed: true }) }
  render() {
    return button
  }
  
  button() {
    let button
    if (this.state.collapsed) {
      button = <Button onClick={this.handleExpandClicked} />
    } else {
      button = <Button onClick={this.handleCollapseClicked} />
    }
    return button
  }
}