React JS Notes

Posted on Posted in Architect, Technologies

This is not suppose to be a comprehensive guide on how to use React JS, but more of a cheat sheet if you need a refresher on how react works.

React Key concepts

  • components structured – Files are separated in what they call components, and each part of the page would have their own js files, for example a page with youtube videos can be broken down like so:
  • each js would require an export to determine which will be used by the main js. for example, search bar would need to export an input type so that the main app js when he imports search_bar he can make use of a input type that is the search bar

Class Based component:

  • we use class based components, if we want a component to maintain some sort of state
  • Note that <class> extends Component
  • Constructor is the class constructor
  • render is what is actually displayed
  • note the export default at the bottom

Functional Components

  • are used for simple components that are used for just displaying, and no need to keep track of state.
  • for example the below, just takes a parameter and displays them as a list <ul>

Component-level State

Class state are a similar concept to object oriented programming, whereas a class has instance variables (state) and they are initialized in the constructor and maintained by the class.

Note that they are only component level state, and the changes are only reflected locally on that js

For example, the below initializes a couple of variables like results, arrayNum, selectedNum, query

True value of React JS is when state is altered, it automatically re-renders the page or it reacts to it.

Importing syntax

when importing from a library provided by react, you can just implicitly say: import React from ‘react’; 

where ‘react’ is the library provided and React is the module you want to import. However if importing from user created js files like importing a search bar from an external js, you have to explicitly state which folder that js is located, see below:

Function Callback

In react you can pass methods to be used by other js. This is a more complex way of passing method, and should be answered really by redux. by for completeness sake, if you are using only react.

for example the below, note the valueSearch method, we declare it in the Main App component, because we want to set the state to change if say the user performs a search.

However, search bar is in a different component other than main app component, hence we passed the valueSearch method via:

<SearchBar onSearchBarQuery={query => this.valueSearch(query)}/>

onSearchBarQuery – is now the new method name in search bar js, which actually just performs the valueSearch.

So if we check search bar again, you have an input type that has a call changeState onChange, which actually performs onSearchBarQuery which in turn calls valueSearch

Leave a Reply