Today we'll begin to rebuild our movies page with React!
JavaScript has a notion of classes similar to other object-oriented languages.
However, quirks abound, because even things that look like keywords
such as class and extends are really just "syntactic sugar" on top
of classic JavaScript. Internally, JavaScript classes are translated into
plain functions in JS.
Here are the main things you should know when writing JS classes:
- Functions inside of a class declaration are called "methods", and they
do NOT use the
functionkeyword. Just omit it. - Use the new-style "arrow function" syntax wherever possible, so that the keyword
thisis more likely to feel more intuitive inside the function. - Use the special function
constructorto initialize instances of your object upon creation.
- React was originally an attempt to bring object-oriented programming to the web
- It has only recently given up on the object-oriented paradigm, preferring a functional approach instead
- Lots and lots of object-oriented React code still exists.
- You should already be comfortable with ES6 "arrow functions" and "object destructuring" syntax (see links below)
- A React "application" is a collection of React components.
- A React component can be a single function or a class.
- Each React component has its own state.
- React components that are classes must define a
render()method to visually draw the component. This method must return a single top-level element (that may contain as many child elements as you want). - A React component that is a function must return a single top-level element (that may contain as many child elements as you want).
- JSX is a React-specific language. It is a JavaScript/HTML hybrid.
- You can embed short JS expressions inside of JSX markup by using curly braces { }
- You can not mix entire ES6 statements (such as loops) inside of JSX but you can use short expressions
- JSX does NOT support
class="..."on an element. UseclassName="..."instead! - JSX will automatically puts quotes around attribute values:
src={image_url} - You can use either JSX or
React.createElement(...)to generate React elements. - React will automatically re-render a component whenever its underlying state changes
React-Specific: