Skip to content

Instantly share code, notes, and snippets.

@hectorlorenzo
Last active November 13, 2020 11:09
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hectorlorenzo/dce4361735103d7892f3cade8a0de1f1 to your computer and use it in GitHub Desktop.
Save hectorlorenzo/dce4361735103d7892f3cade8a0de1f1 to your computer and use it in GitHub Desktop.
Learning React when coming from Vue

Learning React the Vue way

componentDidMount

Part of the component lifecycle, similar to created/mounted.

componentWillUnmount

Part of the component lifecycle, similar to destroyed

Internal state

There is not explicit field that holds the internal state. Instead, we have to rely on the state property (set during the class constructor function).

State can't be modified directly, modifications need to go through setState. This function accepts both a plain object or a function with prevState and props as arguments.

this.setState((prevState) => ({
  items: prevState.items.concat(newItem),
  text: ''
}))

Props

Props are passed from parent to son exactly like in Vue. If the component is functional, props will be passed as an argument of the function. If it's not, we can access it via this.props.

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>
}

Components as classes

To allow React components to be defined as classes (hence having an internal state, among others), we have to use ES6 Classes. One important thing is that we always need to call super(props) in the class constructor. This will call the parent constructor with the new props.

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = {name: 'Hector'}
  }

  render() {
    return <h1>Hello (this.state.name}</h1>
  }
}

Defining functions in a component

Unlike Vue, where "custom" functions go under the 'methods' property, these can be written "anywhere" in the component declaration in React.

class MyComponent extend React.Component {
  constructor (props) {
    super(props)
  }
  
  componentDidMount () {
    this.saySomething()
  }
  
  saySomething () {
    console.log('Something')
  }
}

Binding events

Events are bound as in plain JS:

<button onclick="activateLasers()">
  Activate Lasers
</button>

But camelcasing the event name:

<button onClick={activateLasers}>
  Activate Lasers
</button>

There's something weird we have to do when we define an event handler:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
  
  handleClick () {
    // ...
  }
}

So in the class constructor we need to re-assign the function definition so we can use this on the function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment