Tuesday, September 19, 2017

Class component in React


Functional component

Simple react component which renders a button
const Button= function () {
return (
 <button>Go</button>
);
};
//Syntax to mount a component is ReactDOM.render
//First argument is the component and the second argument is where the 
//component needs to be rendered
ReactDOM.render(<Button/>,mountNode);




Props
React function components receives one argument props.This argument makes the component more reusable
const Button= function (props) {
return (
 <button>{props.label}</button>
);
};
//Syntax to mount a component is ReactDOM.render
//First argument is the component and the second argument 
//is where the component needs to be rendered

Class component : Extends react component

Render(): Function which returns JSX

Simple class component
//Create a class component which extends react component
class Button extends React.Component{
//define the render function. render function is which returns the components Jsx
  render (){
    return (
     <button>54</button>
    );
  }
}
//Syntax to mount a component is ReactDOM.render
ReactDOM.render(<Button label="submit"/>,mountNode);

State in class component
  • To use a state component, we first need to initialize it. This is done in the constructor function which would receive a props function. We need to have a function ex Super within which we initialize this.state 
  • Properties of the state object are the various elements of the state
  • This keyword refers to the component instance
Class component with state
//Create a class component which extends react component
class Button extends React.Component{
//define the render function. render function is which returns the components Jsx
  constructor(props){
   super(props);
   this.state={ counter:10};
  }
  render (){
    return (
     <button>{this.state.counter}</button>
    );
  }
}
//Syntax to mount a component is ReactDOM.render
ReactDOM.render(<Button />,mountNode);

Class component without constructor
class Button extends React.Component{
//define the render function. render function is which returns the components Jsx
 state={ counter:11};
  render (){
    return (
     <button>{this.state.counter}</button>
    );
  }
}
//Syntax to mount a component is ReactDOM.render
ReactDOM.render(<Button />,mountNode);

No comments:

Post a Comment

Labels