React: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
Line 81: Line 81:
class App extends React.Component {
class App extends React.Component {
   constructor(props) {
   constructor(props) {
    super(props);
     this.handleClick = this.handleClick.bind(this);
     this.handleClick = this.handleClick.bind(this);
    super(props);
     this.state = {  
     this.state = {  
       src: VIDEOS.fast  
       src: VIDEOS.fast  

Revision as of 05:18, 26 October 2019

Quick Reference

Variables

 const myVar = (
   <h1>Love it</h1>
 );

Run

Maps

 // Only do this if items have no stable IDs
 
 const todo = ["fix", "syntax", "highlighting"];
 const todoItems = todos.map((todo, index) =>
 <li key={index}>
   {todo.text}
 </li>
);

Component Example

import React, {Component} from 'react';
import ReactDOM from 'react-dom'; 

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: "Frarthur"};
  }
  render() {
    return <div></div>;
  }  
};

Passing Props to child

Parent.json

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

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: 'Frarthur' };
  }

  render() {
    return <Child name={this.state.name} />;
  }
}

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

Child.json

import React from 'react';

export class Child extends React.Component {
  render() {
    return <h1>Hey, my name is {this.props.name}!</h1>;
  }
}

Binding a function

 this.handleClick = this.handleClick.bind(this);

class App extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.state = { 
      src: VIDEOS.fast 
    };
  }

export class Menu extends React.Component {
  render() {
    return (
      <form OnClick={this.props.handleClick}>
        <input type="radio" name="src" value="fast" /> fast
        <input type="radio" name="src" value="slow" /> slow
        <input type="radio" name="src" value="cute" /> cute
        <input type="radio" name="src" value="eek" /> eek
      </form>
    );
  }
}