ReactJS is awesome and you can too!

@MrDanack

Press 'c' to toggle code style
Press 's' for speaker notes

React JS - because full stack devs get paid more

@MrDanack

Press 'c' to toggle code style
Press 's' for speaker notes

The problem - handling forms in PHP sucks

  • layout HTML
  • interactive Javascript
  • displaying errors
  • validation
  • using the data

Symfony/zend forms

Both are pretty terrible

They start off simple, but when you need to do anything complicated they make you less productive than just not using a library, and instead coding everything by hand

I tried to do better

https://github.com/Danack/FirstClassForms

I failed

Javascript libraries?

  • were terrible
  • configuration magic
  • long term viability

Cutting the problem in two

React in browser PHP on the server
Component HTML Page layout HTML
interactive Javascript validation
displaying errors using the data

React Hello World


class HelloElement extends React.Component {
  render() {
    return (
      

Hello {this.props.name}! This is ReactJS.

); } } ReactDOM.render( <HelloElement name="PHPSW" />, document.getElementById('react_hello_element_1') );

React Hello World


<div id="react_hello_element_1"></div>

JSX is Javascript with XML

  • You could write raw JS + HTML....but kind of would be painful
  • These slides are using Babel in browswer compiler
  • For production you would 'want' to use ahead of time compilation

class Clock extends React.Component {
    constructor(props) {
        super(props);
        this.state = {date: new Date()};
    }
    componentDidMount() {
        this.timerID = setInterval(
            () => this.tick(),
            1000
        );
    }
    componentWillUnmount() {
        clearInterval(this.timerID);
    }
    tick() {
        this.setState({
            date: new Date()
        });
    }
    render() {
        return (
            

The time is {this.state.date.toLocaleTimeString()}

); } }

React Clock

This is the code to load it on the page:


     <div id='clock'></div>

An actual form


    formValidate()  {
    let params = "email=" + encodeURI(this.state.email)
      + "&question=" + encodeURI(this.state.question);

    fetch('/ReactJsIntro/validateForm.php?' + params)
      .then((data) => {
          this.setState({
            email_error: data.email_error,
            question_error: data.question_error,
          })
        }
      );
  }

  render() {
    return (
      <div>
        <div>{this.state.email_error}</div>
        <div><input type="text" placeholder="Email" value={this.state.email}
          onBlur={() => this.formValidate()}/> </div>
      </div>
    );

Weather forecast


class WeatherForecast extends React.Component {
  ...
  render() {
    return (
      <div>
        <WeatherSearchBox handler={(city) => this.cityUpdateHandler(city)} />
        <WeatherResults weather_conditions={this.state.weather_conditions} />
      </div>
    );
  }
}



class WeatherResults extends React.Component {
  render() {
    const listItems = this.props.weather_conditions.map((weather_condition) =>
      <ListItem key={weather_condition.dt}
                weather_condition={weather_condition} />
    );
    return (
      <div >
        {listItems}
      </div>
    );
  }
}

function ListItem(props) {
    const wc = props.weather_condition;
    const styles = {width: '100px', marginBottom: "-35px"};

    return (<li><span>{wc.time}
      <img src={"" + wc.icon} style={styles}/> {wc.description} : {wc.temp}
    </span></li>)
}


Testing is easy - real api


const weather_fetcher = function (city, onSuccess) {
  fetch('/getWeather.php?city=' + encodeURI(city))
    .then(handleErrors)
    .then((response) => response.json())
    .then(
      onSuccess
    )
    .catch((err) => {
      alert('error:' + err);
    });
};

ReactDOM.render(
  <WeatherForecast weather_fetcher={weather_fetcher}/>,
  document.getElementById('weather_forecast_mock')
);

Testing is easy - mock api


const weather_fetcher_stub = function (city, onSuccess) {
  let data = [{
    "dt": 12345,
    "temp": "20",
    "time": "Thur 3pm",
    "description": "warm grey",
    "icon": "http://openweathermap.org/img/w/03d.png"
  }];
  onSuccess(data);
};

ReactDOM.render(
  <WeatherForecast weather_fetcher={weather_fetcher_stub}/>,
  document.getElementById('weather_forecast_mock')
);

Weather forecast

React not just in the browser

Server side rendering - compiles with Node

React native - for phones and tablets

Downsides

  • Doesn't play well with others
  • NPM + Javascript ecosystem makes people want to become farmers
  • Will it scale?

Fin

“For years there has been a theory that millions of monkeys typing at random on millions of typewriters would reproduce the entire works of Shakespeare. The Internet has proven this theory to be untrue.”