1. React cheat sheet. Component (class or const). Hooks. Function array.reduce

 1. Create a react application in VStudio

npx create-react-app my-app --template typescript
cd my-app
npm i -D bootstrap


2. Components definition and referencing (const, function, and class) 

2.1 Defining

import React from 'react'

interface Props {
    text: String
    ok?: boolean
    i?: number
    handleChange?: (e: React.ChangeEvent<HTMLInputElement>) => void 
}

// As consts (4 versions)
export const Comp1: React.FC<Props> = ({text}) => <h1>Component 1 with JSX {text}</h1>
export const Comp2: React.FC<Props> = (props) => <h1>Component 2 with JSX {props.text}</h1>

export const Comp3 = (props: Props) => { return(<h1>Component 3 with JSX {props.text}</h1>)}
export const Comp4 = ({text}:Props) => <h1>Component 4 with JSX {text}</h1>

//As function (1 version)
export default function Comp5 ({text}: Props) { return <h1>Component 5 with JSX {text}</h1>}

//As a class
export class Comp6 extends React.Component<Props> {
    props:Props;
    constructor(props:Props) {
        super(props)
        this.props=props;
    }
    render() {
      return <h1>Component 6 with JSX {this.props.text}</h1>;
    }
}

2.1 Referencing const and class (with brackets) and functions (without brackets)

import React from 'react';
import './App.css';
//import {Comp01} from './components/Comp01';
import Comp5, {Comp1, Comp2, Comp3, Comp4, Comp6} from './components/Comp02';
export default function App() {
  return (
    <div className="App">
        {/* <Comp01 b='rrrrrrw'/> */}
        <Comp1 text='my const text 1' /> 
        <Comp2 text='my const text 2' /> 
        <Comp3 text='my const text 3' /> 
        <Comp4 text='my const text 4' /> 
        <Comp5 text='my function text 5' /> 
        <Comp6 text='my class text 6'/>        
    </div>
  );
}

2.1 const vs function, declaration simplicity of const

Usually, functions declared as const can be migrated as functions declared as function, but his example is tricky and I have decided to not migrate the const to function

The purpose of this example is to create a programmatic component TAG, for instance passing the tag as a parameter (tag can be "div", "p", "button", "input", "a"....). It si extracted from StackOverflow

First, a type is created
//HTLM props of a component
type Props = {
  tag?: keyof JSX.IntrinsicElements;
} & React.HTMLAttributes<HTMLOrSVGElement>;


And the problematic const is created as 
//Generic component with tag
const MyGenericComponent: React.FC<Props> = ({ tag: Tag = 'button', children, ...props }) => (
  <Tag {...props}>
    {children}
  </Tag>
);

I have not been able to migrate this const to a function, problems from declaring types have arisen

3. Hooks





import React, { useRef, useState } from 'react'


interface Person {
    firstName: string
    lastName :string
}

interface Props {
    text: String
    ok?: boolean
    i?: number
    handleChange?: (e: React.ChangeEvent<HTMLInputElement>) => void 
    obj?: Person
}


//1. Defining as const
//1.1
export const TextField: React.FC<Props> = ({ text, handleChange}) => {
//1.2
export const TextField =(props.Props) => {

//1.3
export const TextField = ({text, handleChange}: Props) => {

//2. Defining as function
export default function TextField ({text, handleChange}: Props) {

  const [count, setCount] = useState<number>(5)
  const inputRef= useRef<HTMLInputElement>(null)
  const divRef = useRef<HTMLDivElement>(null)
  
    return (
    <div ref={divRef}>
        <input type='text' ref={inputRef} onChange={handleChange} />
    </div>
  )
}


import React from 'react';
import './App.css';

//1.Referencing as const
import {TextField} from "./components/TextField"
//2. Referencing as function import TextField from "./components/TextField" export default function App() { return ( <div className="App"> <h2>Hello world!</h2> <hr></hr> <TextField text='Hello' handleChange={(e) => alert(e.target.value)} /> </div> ); }


3. Component's life cycle in a Class

Only accessible in a class
import React from "react";

type MyState = {name: string}
type MyProps = {message: string}

export class Class01 extends React.Component<MyProps, MyState> {
    state: MyState
    //1. Constructor is called before the component is mounted.
    //   the render method is executed
    constructor(props: MyProps) {
      super(props);
      this.state = { name:'Jalisco'}
      console.log('constructor');
    }
   
    //2.componentDidMount is executed just after the component has been mounted 
    componentDidMount() {
      console.log('componentDidMount')
      this.setState({ name: 'John Doe'})
    }
  
    //3. After componentDidMount, the state is updated, forcing the 
    //   componentDidUpdate execution. The render method is re-executed 
    componentDidUpdate() {
      console.log('componentDidUpdate')
    }
  
    //4. When removing the component from DOM
    componentWillUnmount() {
      console.log('componentWillUnmount')
    }
  
    render() {
      return (<h1>{this.state.name}</h1>);
    }
  }

4. Useful assignations

See more in stackoverflow

/********************************************
* OBJECTS 
*********************************************/
// Assignment in objects, modifying a property
var player = {score: 1, name: 'Jeff'}

var newPlayer = Object.assign({}, player, {score: 2})
// Now player is unchanged, but newPlayer is {score: 2, name: 'Jeff'}


//Assignment in objects, modifying multiple properties
const adrian = {
    fullName: 'Adrian Oprea',
    occupation: 'Software developer',
    age: 31,
    website: 'https://oprea.rocks'
}

//Only modify the desired fields
const bill = {
    ...adrian,
    fullName: 'Bill Gates',
    website: 'https://microsoft.com'
}

/********************************************
* ARRAYS 
*********************************************/
//Copy an array
const squares: Array(9).fill(null)

const squares1 = squares.slice() //Copies squares


5. Array.reduce function

This function is very trucky. In w3schools it is very well explained Let's see some examples

Example 1: 
Convert an array of objects to one object whose attribute names is the value of the "myname" attribute of the objects and the value of the attribute is the value of the attribute "myvalue"

For instance we want to convert this array of objects
[
    { id: '1', myname: 'firstName' , label: 'First Name' , type: 'text' , myvalue: 'Ximo', max:{len:15, message: 'Must be 15 characters or less'}, min:{len:2, message: 'Must be 2 characters or more'}},
    { id: '2', myname: 'lastName', label: 'Last Name', type: 'text', myvalue: 'Dante'},
    { id: '3', myname: 'email', label: 'email', type: 'email', myvalue: 'ximodante@gmail.com'}
]
to this object
{ firstName: 'Ximo', lastname: 'Dante' email: 'ximodante@gmail.com'}

A possible solution to the problem is this code
export function getInitialValues (myFields: fieldAttribute[]) { 
  return (  
    myFields.reduce((obj, item) => {
      obj[item.myname] = item.myvalue;
      return obj;
    }, {} as Record<string, any>)
  );
}

Where myFields is the array of objects that are typified as fieldAttribute( that is a structure I have created previously)


























Comentarios

Entradas populares de este blog

14. Next.js Tutorial (1)

15. Next.js Tutorial (2). Fetching data. Async functions getStaticProps, getServerSideProps, getStaticPaths

17. Next.js Tutorial (4). API Routes