React JS

Instalar React

$ yarn add eslint --dev
$ yarn add react react-dom --dev
$ yarn add @babel/preset-react@^7.0.0 --dev
$ yarn add eslint-plugin-react --dev
$ yarn add prop-types --dev 
$ yarn add babel-plugin-transform-react-remove-prop-types --dev 
$ yarn add sass-loader@^11.0.0 sass --dev 
Agrega este contenido dentro de .eslintrc.js:  

module.exports = { extends: ['eslint:recommended', 'eslint-plugin-react:react/recommended'], parserOptions: { ecmaVersion: 6, sourceType: 'module', ecmaFeatures: { jsx: true } }, env: { browser: true, es6: true, node: true }, rules: { "no-console": 0, "no-unused-vars": 0 } };

Crear App

$ npx create-react-app myapp
$ cd myapp
$ yarn start

// https://saurabhshah23.medium.com/react-js-architecture-features-folder-structure-design-pattern-70b7b9103f22

React & Symfony

En webpack.config.json agregar:
//enable React
.enableReactPreset()

// eliminar proptypes en produccion
.configureBabel((babelConfig) => {
    if (Encore.isProduction()) {
        babelConfig.plugins.push(
            'transform-react-remove-prop-types'
        );
    }
})

React Components

export defualt class AComponent extends React.Component {

    construct(props) {
        super(props);
        this.state = {
            row = null   
        }
    }

    //Este método es obligatorio
    render() {
    }
}

Functional Components

const MyButton = ({ disabled, text }) => (
    
);
MyButton.defaultProps = {
    text: 'My Button',
    disabled: false
};
export default MyButton;

Props y state

Props son valores que recibe el componente que son inmutables, el componente no las va a cambiar
cuando se realiza un evento.
State si las puede cambiar el componente

//Cuando se va a cambiar el state pero se va a utilizar un valor del mismo state se tiene que pasar con una callback
//donde state es el estado actual
this.setState(state => ({
    ...state,
    fourth: state.doneMessage
})

Además hay que crear nuevos objetos cuando queremos modificar un objeto del state, para mantener la inmutabilidad

//...
this.state = {
    data : [
        {//..},
        {//..},
    ]
}

Si queremos agrega un elemento a data hay que hacerlo de esta manera

someFunction() {
    const newData = [...this.state.data, {/...}]
}
Por que si lo hacemos así

const newData = this.state.data;
newData.push({//..})
Estamos modificando el objeto original.


Modificar un objeto dentro de un array manteniendo la inmutabilidad

someFunction(id) {
    this.setState((prevState) => {
        return {
            data: prevState.data.map(d => { -> map nos devuelve una copia (explicacion anterior)
                if (d.id !== id) {
                    return d;
                }
                //Pero dentro de esa copia los objetos son los originales entonces con Object assing devuelve un nuevo objeto donde el 3er objeto es combinado al 2do y el 2do al 1ero
                return Object.assign({}, d, {someProp: true});
            })
      };
});

lifecycles

getDerivedStateFromProps() : This method allows you to update the state of
the component based on property values of the component. This method is called
when the component is initially rendered and when it receives new property
values.
render() : Returns the content to be rendered by the component. This is called
when the component is first mounted to the DOM, when it receives new
property values, and when setState() is called.
componentDidMount() : This is called after the component is mounted to the
DOM. This is where you can perform component initialization work, such as
fetching data.
shouldComponentUpdate() : You can use this method to compare new state or
props with current state or props. Then, you can return false if there's no need to
re-render the component. This method is used to to make your components more
efficient.
getSnapshotBeforeUpdate() : This method lets you perform operations
directly on DOM elements of your component before they're actually committed
to the DOM. The difference between this method and render() is that
getSnapshotBeforeUpdate() isn't asynchronous. With render() , there's a
good chance that the DOM structure could change between when it's called and
when the changes are actually made in the DOM.
componentDidUpdate() : This is called when the component is updated. It's rare
that you'll have to use this method.

Portals

https://reactjs.org/docs/portals.html
A component that should be rendered as a dialog probably
doesn't need to be mounted at the parent. Using a portal, you can control specifically where
your component's content is rendered

Paquetes utiles

$ npm install --save redux-saga
$ npm install --save redux
$ npm i -S react-redux
$ npm i -D redux-devtools