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

Spring Bean Scopes in Dependency Injection

The scope of a bean defines the life cycle and visibility of that bean in the contexts we use it.

The latest version of the Spring framework defines 6 types of scopes:

  • singleton
  • prototype
  • request
  • session
  • application
  • websocket

The last four scopes mentioned, request, session, application and websocket, are only available in a web-aware application.

Let’s create a Person entity to exemplify the concept of scopes:

public class Person {
    private String name;

    // standard constructor, getters and setters
}

Singleton Scope

When we define a bean with the singleton scope, the container creates a single instance of that bean; all requests for that bean name will return the same object, which is cached. Any modifications to the object will be reflected in all references to the bean. This scope is the default value if no other scope is specified.

@Bean
@Scope("singleton")
public Person personSingleton() {
    return new Person();
}

We can also use a constant instead of the String value in the following manner:

@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)

Now we can proceed to write a test that shows that two objects referring to the same bean will have the same values, even if only one of them changes their state, as they are both referencing the same bean instance:

private static final String NAME = "John Smith";

@Test
public void givenSingletonScope_whenSetName_thenEqualNames() {
    ApplicationContext applicationContext = 
      new ClassPathXmlApplicationContext("scopes.xml");

    Person personSingletonA = (Person) applicationContext.getBean("personSingleton");
    Person personSingletonB = (Person) applicationContext.getBean("personSingleton");

    personSingletonA.setName(NAME);
    Assert.assertEquals(NAME, personSingletonB.getName());

    ((AbstractApplicationContext) applicationContext).close();
}

Prototype Scope

A bean with the prototype scope will return a different instance every time it is requested from the container. It is defined by setting the value prototype to the @Scope annotation in the bean definition:

@Bean
@Scope("prototype")
public Person personPrototype() {
    return new Person();
}
private static final String NAME = "John Smith";
private static final String NAME_OTHER = "Anna Jones";

@Test
public void givenPrototypeScope_whenSetNames_thenDifferentNames() {
    ApplicationContext applicationContext = 
      new ClassPathXmlApplicationContext("scopes.xml");

    Person personPrototypeA = (Person) applicationContext.getBean("personPrototype");
    Person personPrototypeB = (Person) applicationContext.getBean("personPrototype");

    personPrototypeA.setName(NAME);
    personPrototypeB.setName(NAME_OTHER);

    Assert.assertEquals(NAME, personPrototypeA.getName());
    Assert.assertEquals(NAME_OTHER, personPrototypeB.getName());

    ((AbstractApplicationContext) applicationContext).close();
}

Web Aware Scopes

There are four additional scopes that are only available in a web-aware application context. We use these less often in practice.

The request scope creates a bean instance for a single HTTP request, while the session scope creates a bean instance for an HTTP Session.

The application scope creates the bean instance for the lifecycle of a ServletContext, and the websocket scope creates it for a particular WebSocket session.

Let’s create a class to use for instantiating the beans:

public class HelloMessageGenerator {
    private String message;
    
    // standard getter and setter
}

Request Scope

@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator requestScopedBean() {
    return new HelloMessageGenerator();
}
@Bean
@RequestScope
public HelloMessageGenerator requestScopedBean() {
    return new HelloMessageGenerator();
}
@Controller
public class ScopesController {
    @Resource(name = "requestScopedBean")
    HelloMessageGenerator requestScopedBean;

    @RequestMapping("/scopes/request")
    public String getRequestScopeMessage(final Model model) {
        model.addAttribute("previousMessage", requestScopedBean.getMessage());
        requestScopedBean.setMessage("Good morning!");
        model.addAttribute("currentMessage", requestScopedBean.getMessage());
        return "scopesExample";
    }
}

Session Scope

@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator sessionScopedBean() {
    return new HelloMessageGenerator();
}
@Bean
@SessionScope
public HelloMessageGenerator sessionScopedBean() {
    return new HelloMessageGenerator();
}
@Controller
public class ScopesController {
    @Resource(name = "sessionScopedBean")
    HelloMessageGenerator sessionScopedBean;

    @RequestMapping("/scopes/session")
    public String getSessionScopeMessage(final Model model) {
        model.addAttribute("previousMessage", sessionScopedBean.getMessage());
        sessionScopedBean.setMessage("Good afternoon!");
        model.addAttribute("currentMessage", sessionScopedBean.getMessage());
        return "scopesExample";
    }
}

Application Scope

@Bean
@Scope(
  value = WebApplicationContext.SCOPE_APPLICATION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator applicationScopedBean() {
    return new HelloMessageGenerator();
}
@Bean
@ApplicationScope
public HelloMessageGenerator applicationScopedBean() {
    return new HelloMessageGenerator();
}
@Controller
public class ScopesController {
    @Resource(name = "applicationScopedBean")
    HelloMessageGenerator applicationScopedBean;

    @RequestMapping("/scopes/application")
    public String getApplicationScopeMessage(final Model model) {
        model.addAttribute("previousMessage", applicationScopedBean.getMessage());
        applicationScopedBean.setMessage("Good afternoon!");
        model.addAttribute("currentMessage", applicationScopedBean.getMessage());
        return "scopesExample";
    }
}

WebSocket Scope

@Bean
@Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator websocketScopedBean() {
    return new HelloMessageGenerator();
}

References
https://www.baeldung.com/spring-bean-scopes