à voir

componentDidMount() componentDidUpdate() componentWillUnmount() et les méthodes comme celles-ci

les events

Sur Codecademy

À copier quand le tuto demande d’effectur un render avec ReactDOM (relou-relou de re-taper)

ReactDOM.render(<Toggle />, document.getElementById('app'))

React ne rend que ce qui a changé.

const hello = <h1>Hello world</h1>;

// This will add "Hello world" to the screen:
ReactDOM.render(hello, document.getElementById('app'));

// This won't do anything at all:
ReactDOM.render(hello, document.getElementById('app'));

Steps

b. A JSX element renders. d. The entire virtual DOM updates. c. The virtual DOM “diffs,” comparing its current self with its previous self. e. Part of the real DOM updates. a. The screen looks different than it used to.

Resources

  • http://braddenver.com/blog/2015/react-static-site.html
  • Alternative à React > https://preactjs.com/
  • Comment structurer des composants dans React > https://reallifeprogramming.com/how-to-structure-components-in-react-54fc43e71546
  • React app w/ React > https://medium.freecodecamp.org/part-1-react-app-from-scratch-using-webpack-4-562b1d231e75
  • Connect React app to REST API > https://www.andreasreiterer.at/connect-react-app-rest-api/

Exercices sur Codecademy

import React from 'react';
import ReactDOM from 'react-dom';

class Contact extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      password: 'swordfish',
      authorized: false
    };
    this.authorize = this.authorize.bind(this);
    
  }

  authorize(e) {
    const password = e.target.querySelector(
      'input[type="password"]').value;
    const auth = password == this.state.password; // renvoie un booléen (cf. le '==') : auth = password, et ensuite, avec '==', on compare avec this.state.password, ce qui renvoie true ou false
    this.setState({
      authorized: auth
    });
  }

  render() {
    const isAuth = this.state.authorized; 
    const login = (<form action="#" onSubmit={this.authorize}>
                   <input type="password" placeholder="Password"/>
                   <input type="submit"/>
                   </form>);
    const contactInfo = (
        <ul>
          <li>
            client@example.com
          </li>
          <li>
            555.555.5555
          </li>
        </ul>
               );
      return(
      
       <div id="authorization">
        <h1>Contact</h1>
        {this.state.authorized ? contactInfo : login} // ternary operator pour décide de ce qu'on affiche, basé sur la valeur de this.state.authorized
      </div>
     );
  }
}

ReactDOM.render(
  <Contact />, 
  document.getElementById('app')
);

props

Pass prop to a component

<Greeting firstName="Esmerelda" someBoolean={true} aNumber={3}/>

Acces component prop

render() {
  return <h1>{this.props.firstName}</h1>;
}

Receive event handler as prop

// file Button.jsx

import React from 'react';

export class Button extends React.Component {
  render() {
    return (
      <button onClick={this.props.talk}> // this was passed from Talker.js
        Click me!
      </button>
    );
  }
}
// file Talker.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import { Button } from './Button';

class Talker extends React.Component {
  talk() {
    let speech = '';
    for (let i = 0; i < 10000; i++) {
      speech += 'blah ';
    }
    alert(speech);
  }
  
  render() {
    return <Button talk={this.talk} />; // we pass prop talk with talk function to Button
  }
}

ReactDOM.render(
  <Talker />,
  document.getElementById('app')
);
// So, Button is rendered THROUGH Talker (the one w/ the method)

Render w/ ReactdOM

ReactDOM.render($what, $where)
ReactDOM.render(<p>Salut</p>, document.getElementById("app"))

diff. HTML JSX elements name

html => jsx class => className for => htmlFor onclick => onClick

Stocker un objet react dans une variable

const toto = (
	<div className={this.props.name}>
		<p>{this.props.name}</p>
	</div>
)

Différentes choses à retourner

On peut retourner plusieurs choses dans un objet React

return(<div></div>) // du html
return({toto}) // une variable
return(<MyComponent/>) // un composant React

Structure type d’un composant React

import 

class
	constructor()
    props1()
	props2()
	render()
	
globalRender`

Exemple

import React from 'react'
import ReactDOM from 'react-dom'

const foo = {
	a: 'bar',
	b: 'manchu'
}

let count = 0;

class Suzie extends Component {
    logAwe(){ // nothing before function name (get, set e.g.) if it does something on its own
    	console.log("Awe "+count);
		count++
    }
    get writeWahou(){ // "get" before, if we get something (like return)
		return "Wahou";
    }
    render(){
		// Si on utilise des fonctions, des variables... Ça vient ici (pas dans class)
	
		let bur = {
			alpha: 420,
			beta: 856
		}
	
		return (
			<div className={foo.b} onMouseOver={this.logAwe}>
				<h1>{foo.a} - {bur.alpha}</h1>
				<p>{this.writeWahou}</p>
			</div>
		)
    }
}

ReactDOM.render(<myComponent />, document.getElementById('app'))

React conditional

{ eval && expression} // si eval == true, alors on passe à l’expression // si eval == false, il ne se passe rien

Lire

  • https://hackernoon.com/react-redux-for-lazy-developers-b551f16a456f
  • https://medium.com/@Connorelsea/using-sass-with-create-react-app-7125d6913760
  • Cache w/ React > https://www.robinwieruch.de/local-storage-react/

Notes on props & state

A React component should use props to store information that can be changed, but can only be changed by a different component.

A React component should use state to store information that the component itself can change.