lifecycle hooks react code example

Example 1: state with react functions

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      

You clicked {this.state.count} times

); } }

Example 2: react lifecycle example

class Test extends React.Component {
  constructor() {
    console.log('Constructor')
    super();
    this.state = {
      count: 0
    };
  }

  componentDidMount() {
    console.log("component did mount");
  }
  componentDidUpdate() {
    console.log("component did update");
  }

  onClick = () => {
    this.setState({ count: this.state.count + 1 });
  };
  render() {
    console.log("render");
    return (
      
Hello Test
); } } //--for first time //Constructor //render //component did mount //--for any update //render //component did update

Example 3: setstate react js

constructor(props) {
        super(props);
        this.state = {
            isActive: true,
        };
    }

    checkStatus = () => {
        this.setState({		// use this function
            'isActive' : !this.state.isActive,
        });
    }

Example 4: set state

setState({ searchTerm: event.target.value })

Example 5: react lifecycle hooks

class Content extends React.Component {
  // ...
  componentWillMount() {
    this.setState({ activities: data });
  }
  // ...
}

Example 6: react lifecycle hooks

class ActivityItem extends React.Component {
  render() {
    const { activity } = this.props;

    return (
      
avatar
{moment(activity.created_at).fromNow()}

{activity.actor.display_login} {activity.payload.action}

{activity.repo.name}
) } }

Tags:

Misc Example