Create Events for React Component

Counter.tsx

import {useState} from "react";

function Counter(props: CounterProp) {
    const [count, setCount] = useState(0)

    const buttonClicked = () => {
        setCount(prevState => {

            var result = prevState + 1;

            if (props.onCounterChanged != null) {
                props.onCounterChanged(result);
            }

            return result;
        })
    };

    return (
        <div>
            <div>Counter Value : {count}</div>
            <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
                    onClick={buttonClicked}>Next
            </button>
        </div>
    );
}

export interface CounterProp {
    onCounterChanged?: (value: number) => void;
}

export default Counter;

App.tsx

import React from 'react';
import Counter from "./components/Counter";

function App() {
    return (
        <div className={"px-1"}>
            <Counter onCounterChanged={(value => console.log(value))}></Counter>
        </div>

    );
}

export default App;

References
https://www.tutorialsteacher.com/typescript/typescript-interface
https://stackoverflow.com/questions/39713349/make-all-properties-within-a-typescript-interface-optional

Handling Events on React

import {useState} from "react";

function Counter() {
    const [count, setCount] = useState(0)

    const buttonClicked = () => {
        setCount(prevState => prevState + 1)
    };

    return (
        <div>
            <div>Counter Value : {count}</div>
            <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
                    onClick={buttonClicked}>Next
            </button>
        </div>
    );
}

export default Counter;

Passing Arguments to Event Handlers

import {useState} from "react";

function Counter() {
    const [count, setCount] = useState(0)

    const buttonClicked = (e: React.MouseEvent<HTMLButtonElement>) => {
        console.log(e);
        setCount(prevState => prevState + 1)
    };

    return (
        <div>
            <div>Counter Value : {count}</div>
            <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
                    onClick={(e) => buttonClicked(e)}>Next
            </button>
        </div>
    );
}

export default Counter;

Prevent default behavior

import {useState} from "react";

function Counter() {
    const [count, setCount] = useState(0)

    const buttonClicked = (e: React.MouseEvent<HTMLButtonElement>) => {
        if (e.cancelable)
        {
            e.preventDefault();
        }

        setCount(prevState => prevState + 1)
    };

    return (
        <div>
            <div>Counter Value : {count}</div>
            <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
                    onClick={(e) => buttonClicked(e)}>Next
            </button>
        </div>
    );
}

export default Counter;

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

For example, this can be useful when:

  • Clicking on a “Submit” button, prevent it from submitting a form
  • Clicking on a link, prevent the link from following the URL

Note: Not all events are cancelable. Use the cancelable property to find out if an event is cancelable.

Note: The preventDefault() method does not prevent further propagation of an event through the DOM. Use the stopPropagation() method to handle this.

References
https://reactjs.org/docs/handling-events.html
https://www.w3schools.com/jsref/event_preventdefault.asp
https://stackoverflow.com/questions/32298064/preventdefault-not-working-in-on-input-function

Pass Children Elements in React using children prop

function FancyBorder(props) {
  return (
    <div className={'FancyBorder FancyBorder-' + props.color}>
      {props.children}    </div>
  );
}

This lets other components pass arbitrary children to them by nesting the JSX:

function WelcomeDialog() {
  return (
    <FancyBorder color="blue">
      <h1 className="Dialog-title">        Welcome      </h1>      <p className="Dialog-message">        Thank you for visiting our spacecraft!      </p>    </FancyBorder>
  );
}

References
https://reactjs.org/docs/composition-vs-inheritance.html
https://reactjs.org/docs/react-api.html#reactchildren

Using the State Hook to Save Component State in React

useState is a Hook that allows you to have state variables in functional components. You pass the initial state to this function and it returns a variable with the current state value (not necessarily the initial state) and another function to update this value.

useState() should only be used inside a functional component.

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"  
const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Equivalent Class Example

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

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

References
https://reactjs.org/docs/hooks-state.html

Components and Props in React

Greeting.tsx

function Greeting(props:GreetingProps) {
    return (
        <p className="px-1 py-4 font-bold text-red-700">Hello {props.name}</p>
    );
}

export interface GreetingProps {
    name:string
}

export default Greeting;

App.tsx

import React from 'react';
import Greeting from "./components/Greeting";

function App() {
  return (
    <Greeting name={"Mahmood"}></Greeting>
  );
}

export default App;

References
https://reactjs.org/docs/components-and-props.html

Conditional Rendering in React JSX

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {    return <UserGreeting />;  }  return <GuestGreeting />;}

Inside return

function List() {
    const people = [
        {id: 1, name: "Mahmood", isAdmin: true},
        {id: 2, name: "Ali", isAdmin: false},
        {id: 3, name: "Javad", isAdmin: false}
    ];

    return (
        <ul>
            {people.map((value, index) => (
                value.isAdmin?(<li key={value.id}>{value.name}</li>):null
            ))}
        </ul>
    );
}

export default List;

Preventing Component from Rendering

function WarningBanner(props) {
  if (!props.warn) {    return null;  }
  return (
    <div className="warning">
      Warning!
    </div>
  );
}

References
https://reactjs.org/docs/conditional-rendering.html

Display Lists in React JSX

function List() {
    const people = [
        {id: 1, name: "Mahmood"},
        {id: 2, name: "Ali"},
        {id: 3, name: "Javad"}
    ];

    return (
        <ul>
            {people.map((value, index) => (
                <li key={value.id}>{value.name}</li>
            ))}
        </ul>
    );
}

export default List;

Keys help React identify which items have changed, are added, or are removed. The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys.

When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort.

References
https://reactjs.org/docs/lists-and-keys.html

Scroll to Top using Javascript

window.scroll({
  top: 100,
  left: 100,
  behavior: 'smooth'
});
var elmnt = document.getElementById("content");
elmnt.scrollIntoView();
var elmnt = document.getElementById("myDIV");
var x = elmnt.scrollLeft;
var y = elmnt.scrollTop;

References
https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll
https://www.w3schools.com/jsref/met_element_scrollintoview.asp
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
https://www.w3schools.com/jsref/prop_element_scrolltop.asp
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop