JSX (JavaScript XML) is an extension to JavaScript syntax used in React. It allows you to write HTML-like code within JavaScript, making it easier to create and manipulate the structure of user interfaces. files got html content in javascript files.
// var ReactDOM = require("react-dom"); dotn need to write this anymore import React from "react"; import ReactDOM from"react-dom";
//ReactDOM.render(WHAT TO SHOW, WHERE TO SHOW) ReactDOM.render(<h1>helloworld</h1>, document.getElementById("root")); // render method can only take one html element
js compiler, it can compile jsx down to plain old js. it can also compile next generation js like es6or7 , down to the version that very browser that could understand.
JSX
JSX is a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript.
It’s typically used with React
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import React from "react"; import ReactDOM from "react-dom";
const name = "Dan";
const num = 12 ;
ReactDOM.render( <div> <h1>Hello {name}!</h1> <p>my lucky number is{ Math.floor( Math.random() * 10 )}</p> </div> , document.getElementById("root")//where to show );
ReactDOM.render() is the entry point into the React application. It takes two arguments:
The React element or component that you want to render.
The DOM element where you want to render the React component.
in JSX, each expression must have a single outermost parent element. This means that when you’re writing JSX, you need to wrap your JSX elements in a single parent element. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// This is valid JSX const element = ( <div> <h1>Hello, world!</h1> <p>This is a paragraph.</p> </div> );
// This is NOT valid JSX const element = ( <h1>Hello, world!</h1> <p>This is a paragraph.</p> );
expression vs. statement
Expressions give you values, while statements do something or control how your code runs.
Expressions in JavaScript produce values. They can be simple, like variables or numbers, or more complex, involving operators or function calls.
Statements in JavaScript perform actions or control the flow of execution. They don’t produce values and consist of keywords, operators, and expressions.
ES6: template literal
**{} (Curly Braces in JSX): **
Used within JSX syntax in React or other libraries/frameworks that utilize JSX.
Used to embed JavaScript expressions or variables within JSX elements.
Allows dynamic values or JavaScript code to be included inside JSX elements. Examples:
1 2
const name = "John"; const greeting = <h1>Hello, {name}!</h1>;
${} (Template Literal Syntax):
Used in regular JavaScript outside of JSX syntax.
Used specifically within template literals (or template strings).
Allows for string interpolation, enabling the embedding of expressions or variables within a string.
1 2
codeconst name = "John"; const greeting = `Hello, ${name}!`;
In the above code, the variable name is interpolated within the template literal using ${}. The value of name is inserted into the resulting string.
To summarize, {} is used in JSX to embed JavaScript expressions within JSX elements, whereas ${} is used in regular JavaScript as part of template literals to interpolate expressions or variables within strings
If Time is a function and you want to export the result of calling that function, you should include parentheses to call it, like Time(). If Time is a variable holding a value, you don’t need parentheses.
import React from "react"; import ReactDOM from "react-dom"; import Time from "./component/Time" ReactDOM.render( <Time/>, document.getElementById("root") );
importReactfrom"react"; importReactDOMfrom"react-dom"; importPIfrom"./math.js"; // will just look for the default export in math.js file, the name(PI), doesn't matter here //but doublePi, triplePi need to be the exact name with the export statemenet
import pi, { doublePi, triplePi } from"./math.js"; // name { doublePi, triplePi } matters here, you need to call the same name as in the export statement
// you can also say: import pi; beasue pi is default export import * as pi from"./math.js"; // you can also say: import * as pi; (import all) ->pi.default pi.doublePi pi.tripleOie() // to call it, just write pi.default pi.doublePi() //wild card(the line above) import is discouraged
ReactDOM.render( <ul> <li>{pi}</li> <li>{doublePi()}</li> // notice: here has parenthesis <li>{triplePi()}</li> </ul>, document.getElementById("root") );
importReactfrom"react"; importReactDOMfrom"react-dom"; import * as pi from"./math.js"; ReactDOM.render( <ul> <li>{pi.default}</li> <li>{pi.doublePi()}</li> <li>{pi.triplePi()}</li> </ul>, document.getElementById("root") );
math.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// export multiple things at once const pi = 3.1415962;
function doublePi() { return pi * 2; }
function triplePi() { return pi * 3; }
export default pi; // can only be one default export per file export { doublePi, triplePi }; // no parenthesis()! // Exporting with different names export { doublePi as doubleValueOfPi, triplePi as tripleValueOfPi };
what this map function does is, it loops through the array of contacts, and for every single item that exists in the array, it called the createCard function and pass each element into the function.
In React, when you use map to render a list of components, it’s essential to assign a unique identifier to each component. This unique identifier is known as a “key.” The purpose of the key is to help React identify which items have changed, are added, or are removed from the list. React uses these keys to optimize rendering performance and to efficiently update the DOM.
var numbers = [3, 56, 2, 48, 5]; //Map -Create a new array by doing something with each item in an array. functiondouble(x) { return x * 2; } const newNums = numbers.map(double);
The substring() method of String values returns the part of this string from the start index up to and excluding the end index, or to the end of the string if no end index is supplied.
const newNumbers = numbers.map(x =>{ return x * x }); const newNumbers = numbers.map((x, y) =>{ return x * y }); // it equals to const newNumbers = numbers.map(function(x){ return x * x ; }); const newNumbers = numbers.map(function(x,y){ return x * y ; });
// var numbers = [3, 56, 2, 48, 5];
// const newNumbers = numbers.map(x => x * x);
//Map -Create a new array by doing something with each item in an array. const newNumbers = numbers.map(function(x) =>{ return x*2; }); // const newNumbers = numbers.map( x => x * 2);
////Filter - Create a new array by keeping the items that return true. // const newNumbers = numbers.filter(num => num < 10);
//Reduce - Accumulate a value by doing something to each item in an array. //const newNumber = numbers.reduce((accumulator, currentNumber) => accumulator + currentNumber);
//Find - find the first item that matches from an array. // const newNumber = numbers.find(num => num > 10);
//FindIndex - find the index of the first item that matches. // const newNumber = numbers.findIndex(num => num > 10);
one approach is fixed (imperative) and the other depends on the state or end result (declarative).
React Hooks
Only call Hooks at the top level: Don’t call Hooks inside loops, conditions, or nested functions. Always use Hooks at the top level of your React functional component or custom Hook. This ensures that Hooks are called in the same order every time a component renders.
Only call Hooks from React functions: You can’t call Hooks from regular JavaScript functions. Hooks should only be called from within React function components or custom Hooks.
In React, a Hook is a special function that allows you to “hook into” React state and lifecycle features from functional components. Before the introduction of Hooks in React 16.8, state and lifecycle methods were only available in class components. With Hooks, you can use state and other React features in functional components without the need for classes.
Hooks are functions provided by React that you can use to add state and other React features to your functional components. They allow you to reuse stateful logic across multiple components without changing the component hierarchy.
Some commonly used React Hooks include:
useState: Allows functional components to use state.
useEffect: Allows functional components to perform side effects (such as data fetching, DOM manipulation) after the component renders.
useContext: Allows functional components to consume context provided by a Context.Provider higher up in the component tree.
useReducer: An alternative to useState for managing more complex state logic with reducers.
useCallback and useMemo: Optimization Hooks for performance optimization by memoizing functions or values to prevent unnecessary re-renders.
useRef: Allows functional components to persist values across renders without causing re-renders.
const CompromisedAccountWarning = ({ hasUnusualActivity, passwordChangedRecently }) => { // State to manage whether the warning should be displayed const [showWarning, setShowWarning] = useState(false);
// Check conditions to determine if warning should be shown if (hasUnusualActivity || passwordChangedRecently) { setShowWarning(true); }
return ( <div> {showWarning && ( <div className="warning"> <p>Your account may be compromised. Please take immediate action.</p> </div> )} </div> ); };