React Lifecycle using Arrow Function

 

React Lifecycle using Arrow Function

 

Changes in index.js

import React from 'react';

import ReactDOM from 'react-dom/client';

import './index.css';

import App from './App';

import reportWebVitals from './reportWebVitals';

 

const root = ReactDOM.createRoot(

  document.getElementById('root')

);

class Lifecycle extends React.Component{

  constructor(){

    super();

    this.state={initialvalue:"Welcome",name:" Students"}

  }

  componentWillMount(){

    alert("Learn ReactJs");

  }

  render(){

    return<div><h1>{this.state.initialvalue}{this.state.name}</h1>

    <br/>

    <button type='button' onClick={this.changevalue}>changevalue</button>

    </div>

  }

  changevalue=()=>{

    this.setState({initialvalue:"Learn ReactJs"});

  }

  componentDidMount(){

  setTimeout(()=>{

    this.setState({initialvalue:"Thank You"})},5000)

 

  }

}

 

var mystyle={color:'green',textAlign:'center'}

const element =<div style={mystyle}><Lifecycle /></div>;

 root.render(element);

 

 

Output






Updating Phase

Updation is the phase where the states and props of a component are updated followed by some user events such as clicking or pressing button.

componentWillUpdate():

Ø The function is invoked before the component is rerendered.

Ø This function gets invoked once before the render() function is executed after the updation of state or props.

 

changes in index.js

import React from 'react';

import ReactDOM from 'react-dom/client';

import './index.css';

import App from './App';

import reportWebVitals from './reportWebVitals';

 

const root = ReactDOM.createRoot(

  document.getElementById('root')

);

class Lifecycle extends React.Component{

  constructor(){

    super();

    this.state={initialvalue:"Welcome",name:" Students"}

  }

  componentWillMount(){

    alert("Learn ReactJs");

  }

  render(){

    return<div><h1>{this.state.initialvalue}{this.state.name}</h1>

    <br/>

    <button type='button' onClick={this.changevalue}>changevalue</button>

    </div>

  }

  changevalue=()=>{

    this.setState({initialvalue:"Learn ReactJs"});

  }

  componentDidMount(){

  setTimeout(()=>{

    this.setState({initialvalue:"Thank You"})},5000)

  }

  componentWillUpdate(){

    alert("Do you want update a new value");

  }

}

 

var mystyle={color:'green',textAlign:'center'}

const element =<div style={mystyle}><Lifecycle /></div>;

 root.render(element);

 

Output








No comments:

Post a Comment