React is a JavaScript library for building user interfaces, particularly single-page applications.
React uses a virtual DOM to efficiently update the user interface. The Virtual DOM is an in-memory representation of the real DOM elements generated by React components. React updates the Virtual DOM whenever the state of a component changes and then determines the most efficient way to update the real DOM to match the Virtual DOM.
The React code is executed in the user’s browser, enabling the creation of more interactive and responsive applications. The applications can update the user interface quickly without needing to refresh the entire page or make frequent server requests.
React Key Ideas
Components
Divide the app into components, and put one in each file
Each component is a function that takes props as input and returns JSX (HTML-like code).
This code defines a React component named App (parent component) using an arrow function. The component returns a JSX structure that includes other components: NavBar, Intro, Photos, and Post (children components).
Props
We pass props from parent component to child component:
1 2
// App.js <Post name="Kenneth" text="Welcome to web lab!" /> // inside parent component
React uses className instead of class for CSS style.
What the component function returns is what to be rendered.
What inside return() uses JSX syntax (HTML-like code).
JSX Syntax
We can write HTML in JSX environment.
Parentheses () allow us to enter a JSX environment.
Inside the JSX environment, curly braces {} allow us to create a mini JavaScript environment.
State
State is data maintained by a component and is mutable. State can be kept in parent components so that it can be passed into reusable child components as props.
When clicking on the Like button, the state variable isLiked will be changed to true, and “Liked” will be displayed.
useState(false) returns two values. isLiked: The initial state value, set to false. setIsLiked: A function that lets you update the isLiked state.
Calling setIsLiked(true) will set isLiked to true and trigger a re-render.
State variable can only be modified through the set function, i.e., we can’t do isLiked = false, we should do setIsLiked(false). Another example is that if a state is an array, and to add a new element to the array, we should do setXXX(XXX.concat(data)) because .concat() will create a new array without directly modifying the original array.
constPhotos = (props) => { const myImageTags = props.links.map((photoLink) => { // map an array of string to an array of html contents return<imgsrc={photoLink} />; });