Basic React Function Component

Posted on

in

,

This is a copy of this post, but using a function component and hooks.

import React, { useState, useEffect } from 'react';

import "./ConditionalClass.css"

function FunctionComponent(props) {

  const [con1, toggleCon1] = useState(false);
  const [con2, toggleCon2] = useState(false);

  useEffect(() => {
    //replaces componentDidUpdate() in class components. happens after render
    console.log("change");

    return function cleanup() {
      console.log("cleanup"); //similar to componentWillUnmount()
    }

  }, []) // <-- add [] to change it to act like componentDidMount(). By declaring no dependencies, there's nothing to check to see if it changed, so it never reruns

  return (
    <div>
      <button onClick={() => toggleCon1(!con1)}>toggle 1</button>
      <button onClick={() => toggleCon2(!con2)}>toggle 2</button>

      <div className={`defaultClass ${con1 ? "con1" : ""} ${con2 ? "con2" : ""
        }`}>
        something
      </div>
    </div>
  )
}

export default FunctionComponent;

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

May 2024
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031