paddockpass/react/NOTES.md
2019-09-27 15:13:37 +02:00

2.4 KiB

Notes

Props

Props stands for properties. A system for passing data from a parent component to a child component. The goal is to customize or configure the child component.

Props are objects so the fields have to be called as methods: props.author for instance.

It is possible to use defaultProps to instantiate the default behaviour of a component.

Functional components

Used anytime to show simple content to the user. (the card for example -- create JSX pass some props and return it).

Alternative writing:

const SearchBar = () => (
    <div></div>
)

Class components

For complex content, respond to user input, network request. Can use the state input.

Class components are not classes in terms of Ruby or Python, they are a Javascript Class. They also must be extended to a subclass (react component). And they must define a render method that returns some amount of JSX.

When components are reloaded they are also reloading the child components.gt

State

Rules

  • Only usable with class components (not always true)
  • state =/= props
  • State is a JS object that contains data relevant to a component
  • Updating state on a component causes the component to almost instantly rerender
  • State must be initialized when a component is created
  • State can only be updated with the setState function

Video 61: refactorisation on state and constructors, you can remove the whole constructor by passing a state to the class. => what is the state in a react application? Code is passed to Babel and understand the code that is compiled and extends + implements the constructor function.

     constructor(props) {
         super(props)
         this.state = { lat: null, errorMessage: '' }
     }
  • always try to have one statement in the render method, in case it isn't possible try to use a helper function with the complex cases and returning to the render method. see video 70

  • onInputChange: In that case:

    <input type="text" onChange={this.onInputChange}>

The function onInputChange is not called as a function (onInputChange()) but as a callback so the function is not run everytime the component is rendered but when the component is called. Other functions: onClick, onSubmit and onChange

  • replace handlers by arrow functions, insead of:
    <input type="text" onChange={this.onInputChange}>

you get:

    <input type="text" onChange={(e) => console.log(e.target.value)}>