Skip to content

Instantly share code, notes, and snippets.

@audrow
Created December 16, 2021 15:26
Show Gist options
  • Save audrow/e9fb3247e29086ab189f7bae8c91728d to your computer and use it in GitHub Desktop.
Save audrow/e9fb3247e29086ab189f7bae8c91728d to your computer and use it in GitHub Desktop.
Free Code Camp's React tutorial #course #webdev

Free Code Camp React Tutorial

  • React lets you compose your UI from many separate, isolated compontents, which makes building and maintenence easier

  • Syntax

    • Valid JSX must be inside of a single element
    • JSX looks like HTML with Javascript in curly braces
      • Valid comments are structured as follows: {/* my comment */}
      • class in html becomes className
      • Use camel case for naming convention, like onClick and onChange
      • Every tag must be self-closing (<br />) or closed (<div> </div>), but it cannot be left open (<br> must be <br/>)
      • Functions must begin with a capital letter, e.g., DemoComponent
    • To include child as component, reference it in self-closing tags
  • Rendering

    • Render with ReactDOM.render(component, targetNode)
      ReactDOM.render(JSX, document.getElementById('challenge-node'))
    • Components
      ReactDOM.render(<ComponentToRender/>, targetNode)
  • Compontents

    • Can be defined in a function that returns JSX or null
    • Can be defined in a class that extends React.Component and has a constructor (which passes props and passes props to super()) and render method
      class MyComponent extends React.Component {
        constructor(props) {
          super(props)
        }
        render() {
          return (
            <div>
            <h1>My First React Component!</h1>
            </div>
          )
        }
      }
      
      ReactDOM.render(<MyComponent/>, document.getElementById('challenge-node'))
    • It's standard to use props when dealing with stateless components
      const Welcome = (props) => <h1>Hello, {props.user}!</h1>
      <App>
        {/* Usage */}
        <Welcome user='Mark' />
      </App>
      • Use this.props when accessing props in an ES6 class
    • Arrays can be used with the following syntax:
      <ParentComponent>
        <ChildComponent colors={["green", "blue", "red"]} />
      </ParentComponent>
    • Pass integers and non strings in curly braces, to have them interpreted by javascript, for example <Items quantity={10} />
    • Set default arguments:
      MyComponent.defaultProps = { location: 'San Francisco' }
    • Use prototypes to set the types of props in advance (reference])
      MyComponent.propTypes = { handleClick: PropTypes.func.isRequired }
  • State in components

    • Typical pattern is to minimize components with state
    • If your data changes, React will trigger an update of the virtual DOM, but only when necessary
    • Note, no other components are aware of another components state, unless they are directly passed to the component
    • Declare state in constructor
      this.state = {key: "value"}
    • Access state with
      this.state
      
    • React expects you to never modify state directly, so set the state with this.setState({ key: value })
      • Can also take a function, see here
      • If you are relying on props or state, use a function to set the state:
        this.setState((state, props) => ({
          counter: state.counter + props.increment
        }))
        • Note, the parenthesis are necessary so that Javascript doesn't think the object is a block of code
    • Modifying state in functions
      • Option 1: regular class function -> explicitly bind in constructor
        class MyComponent extends React.Component {
          constructor(props) {
            super(props);
            this.state = { text: "Hello" };
            this.handleClick = this.handleClick.bind(this)
          }
          handleClick() {
            this.setState({ text: "You clicked!" });
          }
          render() {
            return (
              <div>
              <button onClick={this.handleClick}>Click Me</button>
              <h1>{this.state.text}</h1>
              </div>
            );
          }
        };
      • Option 2: use the arrow syntax
        class MyComponent extends React.Component {
          constructor(props) {
            super(props);
            this.state = { text: "Hello" };
          }
          handleClick = () => {
            this.setState({ text: "You clicked!" });
          }
          render() {
            return (
              <div>
              <button onClick={this.handleClick}>Click Me</button>
              <h1>{this.state.text}</h1>
              </div>
            );
          }
        };
  • Working with forms

    • Handling changes in text boxes - pass the event to a function and use that state value as the value in the text entry element
      handleChange(event) {
        this.setState({
          input: event.target.value
        });
      }
    • Handling submit form full example
      class MyForm extends React.Component {
        constructor(props) {
          super(props);
          this.state = {
            input: '',
            submit: ''
          };
          this.handleChange = this.handleChange.bind(this);
          this.handleSubmit = this.handleSubmit.bind(this);
        }
        handleChange(event) {
          this.setState({
            input: event.target.value
          });
        }
        handleSubmit(event) {
          event.preventDefault()
          this.setState(state => ({
            submit: state.input
          }))
        }
        render() {
          return (
            <div>
            <form onSubmit={this.handleSubmit}>
              <input value={this.state.input} onChange={this.handleChange}/>
              <button type='submit'>Submit!</button>
            </form>
            <h1>{this.state.submit}</h1>
            </div>
          );
        }
      }
  • Passing state and callbacks as props in components

    • Important paradigms in React
      • State flows down the tree of your applications components
      • Complex stateful apps can be broken down into just a few, or maybe a single, stateful component - with the rest of the components receive state from their parents as props
        • This separates state logic from UI logic, which makes complex, stateful applications easier to manage
    • Passing callbacks is how children can influence parents
  • Lifecycle methods (or hooks)

    • Main methods: componentWillMount() componentDidMount() shouldComponentUpdate() componentDidUpdate() componentWillUnmount()
    • The componentDidMount() hook
      • Place API calls here, so that it will call the API and update the component once it has the data
      • Add event listeners for the document or window here
        • React provides a synthetic event system, that wraps the native event system in browsers
    • shouldComponentUpdate(nextProps, nextState): bool
      • You can make it so that rerendering doesn't occur if the props are the same
      • Can compare this.props to nextProps to look for differences
  • Styling components

    • You can use className in html elements
    • In general, use camelCase for styling, because JSX doesn't do hyphens (-)
    • React assumes numbers for size are in pixels, unless specified
    • Or use a dictionary to provide the styling:
      <div style={{color: "red", fontSize: "72px"}}>Big Red</div>
  • Using conditional logic

    • Can have multiple return statements in render, or have inline bools, like the following, which will only display if this.state.display is true
      {this.state.display && <h1>Displayed!</h1>}
      or using ternary operator, is fine too (can have ternary in ternary) jsx {this.state.userAge === '' ? buttonOne : this.state.userAge >= 18 ? buttonTwo : buttonThree}
    • Use maps to modify many objects
      const items = this.state.toDoList.map(i => <li key={i}>{i}</li>)
    • User ReactDOMServer.renderToString to send react from server to client
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment