User Tools

Site Tools


react.js

React.js

React Devtools extension.

If component does not have state, does not have user interaction, is not top-level component, use function component. Otherwise, use class component.

Use 'axios' library for AJAX requests.

  // Not so good, cos setState is async and could make race condition.
  handleClick = () => {
  	this.setState({
    	counter: this.state.counter + 1
    });
  };
 
  // Fixed. Only needed if accessing current (prevState) state.
  handleClick = () => {
  	this.setState((prevState) => {
    	counter: prevState.counter + 1
    });
  };

Intro example

class Button extends React.Component {
  handleClick = () => {
  	this.props.onClickFunction(this.props.incrementValue)
  };
 
	render() {
    return (
      <button
      	onClick={this.handleClick}>
      	+{this.props.incrementValue}
      </button>
    );
  }
}
 
const Result = (props) => {
	return (
  	<div>{props.counter}</div>
  );
};
 
class App extends React.Component {
  state = { counter: 0};
 
  incrementCounter = (incrementValue) => {
  	this.setState((prevState) => ({
    	counter: prevState.counter + incrementValue
    }));
  };
 
	render() {
  	return (
    	<div>
      	<Button incrementValue={1} onClickFunction={this.incrementCounter} />
      	<Button incrementValue={5} onClickFunction={this.incrementCounter} />
      	<Button incrementValue={25} onClickFunction={this.incrementCounter} />
      	<Button incrementValue={100} onClickFunction={this.incrementCounter} />
        <Result counter={this.state.counter} />
      </div>
    );
  }
}
 
ReactDOM.render(<App />, mountNode);

Module 2 - Build a Github Card Component

// https://gist.github.com/samerbuna/57d8c2bd754ebb2359fa39cc8dea999d
// Function component.
const Card = (props) => {
  return (
    <div style={{margin: '1em'}}>
      <img width="75" src={props.avatar_url} />
      <div style={{display: 'inline-block', marginLeft: 10}}>
        <div style={{fontSize: '1.25em', fontWeight: 'bold'}}>
          {props.name}
        </div>
        <div>{props.company}</div>
      </div>
    </div>
  );
};
 
let data = [
  { name: "Paul O’Shannessy",
    avatar_url: "https://avatars.githubusercontent.com/u/8445?v=3",
    company: "Facebook" },
  { name: "Ben Alpert",
    avatar_url: "https://avatars.githubusercontent.com/u/6820?v=3",
    company: "Facebook" },
];
 
// Function component.
const CardList = (props) => {
  return (
    <div>
      {props.cards.map(card => <Card {...card} />)}
      // Spread operator  ------------^^^ deconstructs a JS object into parameters. Simplifies this:
      //{props.cards.map(card => <Card name={card.name}... />)}
    </div>
  );
}
 
ReactDOM.render(<CardList cards={data} />, mountNode);

Module 2 - Taking Input from the User

const Card = (props) => {
  return (
    <div style={{margin: '1em'}}>
      <img width="75" src={props.avatar_url} />
      <div style={{display: 'inline-block', marginLeft: 10}}>
        <div style={{fontSize: '1.25em', fontWeight: 'bold'}}>
          {props.name}
        </div>
        <div>{props.company}</div>
      </div>
    </div>
  );
};
 
const CardList = (props) => {
  return (
    <div>
      {props.cards.map(card => <Card key={card.id} {...card} />)}
      // React likes to have a unique key ^^^^^^^ for some reason.
    </div>
  );
};
 
class Form extends React.Component {
  state = { userName: '' }
  handleSubmit = (event) => {
    event.preventDefault();
    axios.get(`https://api.github.com/users/${this.state.userName}`)
      .then(resp => {
        this.props.onSubmit(resp.data);
        this.setState({ userName: '' });
      });
  };
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input type="text"
          value={this.state.userName}
          onChange={(event) => this.setState({ userName: event.target.value })}
          placeholder="Github username" required />
        <button type="submit">Add card</button>
      </form>
    );
  }
}
 
class App extends React.Component {
  state = {
    cards: []
  };
 
  addNewCard = (cardInfo) => {
    this.setState(prevState => ({
      cards: prevState.cards.concat(cardInfo)
    }));
  };
 
  render() {
    return (
      <div>
        <Form onSubmit={this.addNewCard} />
        <CardList cards={this.state.cards} />
      </div>
    );
  }
}
 
ReactDOM.render(<App />, mountNode);
react.js.txt · Last modified: 2017/09/21 00:58 by stephen