State basics

props which are passed into component as static vals or methods, state is meant to be managed by the component itself.

setup of state:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      txt: 'this is the state text'
    }
  }

  render() {
    return <h1>{this.state.txt}</h1>
  }
}

manage the state

you can update the state by adding the following method:

update(e) {
  this.setState({
    txt: e.target.value
  })
}

now lets add an input into our render functon with an onChange property:

render() {
  return (
    <div>
      <input type="text"
        onChange={this.update.bind(this)} />
      <h1>{this.state.txt}</h1>
    </div>
  );
}

now if we type into the input it will update the h1 automatically, behaving somewhat like a simple angular 2-way binding.

Owner Ownee Relationship

the parent component is also called a composite component

first off, in our previous example, we can add a property onto our constructor() method:

constructor() {
  super();
  this.state = {
    txt: 'this is the state text',
    cat: 0
  }
  this.update = this.update.bind(this)
}

now in our render function we can change onChange={this.update.bind(this)} to just onChange={this.update}

Next lets factor our code that currently in render() into its own component, which will be a state function component:

const Widget = (props) => {
  return (
    <div>
      <input type="text"
        onChange={props.update} />
      <h1>{props.txt}</h1>
    </div>
  );
}

now in our render function we can do:

render() {
  return (
    <div>
      <Widget txt={this.state.txt} update={this.update} />
    </div>
  );
}

using refs to access components

refs are a way to reference an instance of a component from within our react app. In our current app, when we type into an input it updates ALL of the instances, instead we want it to update just one instance.

we are gonna create a …

first lets create a slide component, removing the Widget component:

class Slider extends React.Component {
  render() {
    return (
        <input type="range"
          onChange={this.props.update}
          min="0"
          max="255" />
    );
  }
}

now lets change the constructor in App to:

this.state = {
  red: 0,
  green: 0,
  blue: 0
}

lets change App.render() to the following:

<div>
  <Slider ref="red" update={this.update} />
  <Slider ref="green" update={this.update} />
  <Slider ref="bue" update={this.update} />
</div>

where ref can be accessed by ReactDOM.findDOMNode(this.ref.red).value.

then lets change the update(e) function to reflect the changes:

update(e) {
  this.setState({
    red: ReactDOM.findDOMNode(this.ref.red).value,
    green: ReactDOM.findDOMNode(this.ref.green).value,
    blue: ReactDOM.findDOMNode(this.ref.blue).value
  })
}

Accessing Child Properties

example of accessing nested components with {this.props.children}