liveBook · Manning

Class method

As explained in React Quickly, Second Edition

A class method is a function defined as part of a class that can access the class or instance context in which it is invoked.

A class method is a function defined inside a class. In a React image component, getImageSource can either accept an index or read this.props.index directly. section 4.4.2 section 4.4.3

Building an image URL

class Image extends Component { getImageSource() { return `//picsum.photos/id/${this.props.index}/150/150/`; } render() { return <img src={this.getImageSource()} alt={this.props.title} />; } } Here, the method uses this.props directly, so it is tied to the class instance. A method that receives index instead and uses only that argument is a pure utility function. section 4.4.2

Choose the form that matches the method's dependence on component context:

  • Use a class method with arguments when the function is only a utility: getImageSource(index). It can move outside the class without changing its result. section 4.4.2
  • Use a context-dependent class method when it reads component properties: getImageSource() uses this.props.index and is called as this.getImageSource(). section 4.4.3
  • When converting to a functional component, pass the required values to a pure function or define a local function that closes over component values. section 4.4.3

How React Quickly, Second Edition covers it

How deep it goes
Distinguishes pure utility methods from instance-dependent methods and compares their functional-component conversions.
Examples
Uses an image gallery, getImageSource, image URLs, this.props.index, and equivalent class-to-function implementations.
What it assumes
Assumes basic class, function, JSX, component, and props familiarity while contrasting context-free and context-dependent helpers.
What you can do after
Apply class methods to simplify JSX and convert them into pure or local functions when building functional components.
How it connects
Connects class methods with React class components, props, JSX, pure functions, and functional components.

Also explained in

Compare how 3 books explain class method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.