What Methods Are in React?

 What Methods Are in React?


What Methods Are in React?


Introduction

React is a very popular choice when building a SPA, Single Page Application. A Single Page Application differs from a normal web application in that you remain on the same URL and thereby the same page, hence the name. To create many pages in a Single Page Application we instead use the hash, # and listen to changes on it, for example, http://myapp.com#/products and http://myapp.com#/users are considered different pages in a Single Page Application. React was created by Facebook. The official documentation can be found at, https://reactjs.org/

React lets us define components as classes or functions. Components defined as classes currently provide more features which are described in detail on this page. To define a React component class, you need to extend React. Component:

class Welcome extends React. Component {

render() {

return Hello, {this.props.name};

}

}

The only method you must define is React.Component subclass is called render(). All the other methods described on this page are optional.

Methods

When we build our component we are going to want to add methods to it. We are going to attach methods to different events for example submits, click, change, etc. One thing we need to keep in mind is that React changes the name and the casing of the event like so:

  • click becomes onClick
  • change becomes onChange
  • submit becomes onSubmit

Event examples

Let's have a look at how to set up a method to an event:

class Element extends React.Component {

clicked() {

console.log('clicked');

}

render() {

return (

)

}

}

Binding our method to our class

This looks all well and good but it has a problem. You don't see the problem right now cause it does what it is supposed to i.e print clicked in the console. However, try to do the following modification:

class Element extends React. Component {

state = {

str: 'test'

}

clicked () {

console.log ('clicked ' + this.state.str);

}

render () {

return (

)

}

}

The above code WILL give out an error as it doesn't know what the state is. This is because these points wrong. There are several ways to fix this. Let's look at the first one:

class Element extends React. Component {

constructor() {

super();

this.clicked = this.clicked.bind(this);

}

state = {

str: 'test'

}

clicked() {

console.log('clicked ' + this.state.str);

}

render() {

return (

)

}

}

We are above declaring a constructor and binding our method clicked() to the object instance, like so:

constructor() {

super();

this.clicked = this.clicked.bind(this);

}

Powered by Blogger.