react class based component vs classes in java

Tags: ,



I’m newish to react and I’ve always thought of a class based component much like I do classes in Java.

Is it correct to compare the two thinking of the class based component and class in Java? In other words, are rendered components like objects in Java where they are an instantiation of the class?

Are there differences?

Answer

The one major thing to note as highlighted in the docs is that thinking about OOP (and inheritance to be specific) is that we do not extend classes like you would do in Java.

What does it mean? Lets take this simple example from this answer:

public class ExtendedButton extends Button {
    public ExtendedButton() {
        super();
        styleProperty().bind(Bindings.
                when(buttonState.isEqualTo(ButtonState.CRITICAL)).
                then("-fx-base: red;").
                otherwise(""));

    }
}

An example of this in react would have two main differences.

  • The ExtendedButton would extend React.Component instead of Button
  • Therefore you wont have access to Button.prototype but you can use composition as shown below.

Core Bootstrap Button

class Button extends React.Component {
    render() {
      return (
        <button className=`btn btn-{this.props.btnType}` onClick={this.props.handleClick}>
          { this.props.label} 
        </button>
       )
    }
}

Primary Bootstrap Button

class PrimaryButton extends React.Component {
    render() {
      return (
        <Button btnType="default" handleClick={this.props.handleClick} label={ this.props.label} />
       )
    }
}

This would be the way someone would start writing the bootstrap buttons. This is simplified though and composition can get more interesting as you get to understand it. Consider checking out the whole article in the documentation talking about Composition vs Inheritance



Source: stackoverflow