React components: Difference between revisions

From wikinotes
Line 91: Line 91:
</blockquote><!-- Element Variables -->
</blockquote><!-- Element Variables -->
</blockquote><!-- Attributes -->
</blockquote><!-- Attributes -->
= Return Types =
<blockquote>
React requires that a single top-level element is returned by each component.<br>
There are two variations of this that allow you to return multiple types.
== Lists ==
<blockquote>
</blockquote><!-- Lists -->
== Fragments ==
<blockquote>
</blockquote><!-- Fragments -->
</blockquote><!-- Return Types -->


= Lifecycle Methods =
= Lifecycle Methods =

Revision as of 23:37, 22 August 2021

Components

Component Functions

function Description() {
    return (
        <h1>Description</h1>
        <p>{this.props.paragraph}</p>
    )
}
<Description paragraph="a very long..." />

Component Classes

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

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

Attributes

this.props

Parameters are passed parameters using xml tag attributes.
Within the component, they are axposed as attributes on the this.props variable.

ReactDOM.render(
    <Description name="Alex" />,         // <-- use component
    document.getElementById('root')
);
function Description() {
    return <p>hello, {this.props.name}</p>;  // <-- access props in component
}

this.state

this.state is a special object property to store UI related info.
The component will be re-rendered every time the this.setState() is called.

class Thing extends React.Component {
    constructor(props) {
        super(props);
        this.state = { collapsed: false };
    }

    render() {
        if (this.state.collapsed) {
            <p>collapsed</p>
        } else {
            <p>expanded</p>
        }
    }
}
this.setState()

Return Types

React requires that a single top-level element is returned by each component.
There are two variations of this that allow you to return multiple types.

Lists

Fragments

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>
    );
  }
}