Skip to content
coloradokim edited this page Apr 2, 2018 · 6 revisions

React

Grab Bag from Wes Bos's React for Beginners

  • New feature: to next elements in JSX, wrap everything in React.Fragments()
  • Stateless functional components (?)
  • State is like the grocery store and props is like the van that delivers the groceries you've ordered
  • ref = reference, a html attribute that you name and determine the value of
  • return () helps avoid automatic semi-colon insertion at the end of a line

Components

  • A react component is a function that returns one React element
  • React component names should be capitalized (i.e. Greeting)

An example of a React Component:

import React from 'react';

const SayHello = () => {
  return <h1>Hello!</h1>;
};

export default SayHello;

or

import React from 'react';

class SayHello extend React.Component {
  render() {
    return (
      <h1>Hello!</h1>
    )
  }
}

export default SayHello;

React Elements

  • Make a component a self-closing HTML tag
import React from 'react';
import SayHello from './SayHello';

const wrapper = () => {
  return (
    <div>
      <SayHello />
    </div>
  );
};

export default Wrapper;

Props

In React, you can use components to render data through the props object. For example, to make our SayHello compent reactive to user input, we pass in data via props.

import React from 'react';

const SayHello = props => {
  return <h1>Hello {props.name}!</h1>;
};

export default SayHello;

Then, we would render the component like this:

<SayHello name="Catherine" />
<SayHello name="Jeremiah" />

The best practice in React development is to use the ES6 destructuring feature. Here's the SayHello component with destructuring:

import React from 'react';

const SayHello = ({ firstName, lastName }) => {
  return (
    <h1>
      Hello {firstName} {lastName} !
    </h1>
  );
};

export default SayHello;

To render the component with this data:

<SayHello firstName="Catherine" lastName="Schlesinger" />
<SayHello firstName="Jeremiah" lastName="Rose" />

State

  • In React, state is an object that represents your data
Clone this wiki locally