React
Why can't you use the word 'class' in JSX? Are HTML & JSK the same?
They are NOT; 'class' is a reserved word in JavaScript. JSX uses 'className' instead. - In fact, the naming convention for all HTML attributes and event references in JSX become camelCase. For example, a click event in JSX is onClick, instead of onclick. Likewise, onchange becomes onChange.
What is a stateless functional component and how would we write one?
Think of a stateless component as one that can receive data and render it, but does not manage or track changes to that data. E.G. Here's an example of a stateless functional component that assigns an HTML class in JSX: // After being transpiled, the <div> will have a CSS class of 'customClass' const DemoComponent = function() { return ( <div className='customClass' /> ); };
How do we write comments in JSX?
To put comments inside JSX, you use the syntax {/* */} to wrap around the comment text.
What is ReactDOM?
We can use React's rendering API, known as ReactDOM, to render JSX directly to the HTML DOM. - ReactDOM offers a simple method to render React elements to the DOM which looks like this: ReactDOM.render(componentToRender, targetNode) -> where the 1st argument is the React element or component that you want to render -> the 2nd argument is the DOM node that you want to render the component to. - ReactDOM.render() must be called after the JSX element declarations, just like how you must declare variables before using them
How would we initialize state in a Class Component?
class Clock extends React.Component { constructor(props) { super(props); this.state = { } }
**An Example of Nested Components**
class Fruits extends React.Component { constructor(props) { super(props); } render() { return ( <div> <h2>Fruits:</h2> { /* Change code below this line */ } <NonCitrus/> <Citrus/> { /* Change code above this line */ } </div> ); } }; class TypesOfFood extends React.Component { constructor(props) { super(props); } render() { return ( <div> <h1>Types of Food:</h1> { /* Change code below this line */ } <Fruits/> { /* Change code above this line */ } <Vegetables /> </div> ); } };
What is an ES6 class syntax component? An Example?
class Kitten extends React.Component { constructor(props) { super(props); } render() { return ( <h1>Hi</h1> ); } } - This creates an ES6 class Kitten which extends the React.Component class. So the Kitten class now has access to many useful React features, such as local state and lifecycle hooks. - Also notice the Kitten class has a constructor defined within it that calls super(). It uses super() to call the constructor of the parent class, in this case React.Component. The constructor is a special method used during the initialization of objects that are created with the class keyword. It is best practice to call a component's constructor with super, and pass props to both. This makes sure the component is initialized properly.
What would ES6 arrow functional syntax look like for a component called ChildComponent that returns a <div> and a nested <p> ?
const ChildComponent = () => { return ( <div> <p>I am the child</p> </div> ); };
How would we target the DOM node that we wish to render a React component or element into?
document.getElementById( ) E.g. ReactDOM.render(JSX, document.getElementById('challenge-node') );
How would we prevent a default event in React.js?
e.g.
How would we import a hook? (e.g. import the useState hook)?
import React, { useState } from 'react';
How can we represent the DOM with React?
we can use: ReactDOM.render(JSX, document.getElementById('root')). This function call is what places your JSX into React's own lightweight representation of the DOM. React then uses snapshots of its own DOM to optimize updating only specific parts of the actual DOM.
How would we use this.state correctly in React.js?
- 1) The only place where you can assign this.state is in the constructor e.g. // Correct this.setState( {comment: 'Hello'} );
If state can be updated asynchronously, how should we handle it?
- Because state may be updated asynchronously, we should NOT rely on their values for calculating the next state. It's best to use a FUNCTION to receive the previous state as the 1st argument, and the props at the time the update is applied as the 2ND argument. e.g. Arrow Function syntax: // Correct this.setState((state, props) => ( { counter: state.counter + props.increment } )); E.g. Regular Function syntax: // Correct this.setState(function(state, props) { return { counter: state.counter + props.increment }; });
What is "unmounting" a component in React.js?
- E.g. We also want to clear that timer whenever the DOM produced by the Clock is removed. - when we remove the component from the DOM - **(think of it as "clean up")
What does " componentWillUnmount ( ) " do? What's its utility?
- E.g. We will tear down the timer in the componentWillUnmount() lifecycle method: componentWillUnmount() { clearInterval(this.timerID); } - Analogy: At a picnic, componentWillUnmount corresponds to just before you pick up your picnic blanket. You would need to clean up all the food and drinks you've set on the blanket first or they'd spill everywhere! You'd also have to shut down your radio. After that's all done you would be free to pick up your picnic blanket and put it back in the bag safely. For a React component, this is where you would clean up any of those long running processes that you set up in componentDidMount.
What is "mounting" a component in React.js?
- Eg. When we render a component to the DOM for the first time, it's called "Mounting" (**Think of it as "setup") E.g.We want to set up a timer whenever the Clock is rendered to the DOM for the first time.
What is a React Hook?
- Hooks let you use state and other React features without writing a class - They are functions that let you "hook into" React state and lifecycle features from function components. Hooks don't work inside classes — they let you use React without classes.
What is a lifecycle method in React.js?
- Special methods on the component class that run some code when a component mounts and unmounts.
Describe the concept of "The Data Flows Down"
- State is often called local or encapsulated. It is not accessible to any component other than the one that owns and sets it. This is commonly called a "top-down" or "unidirectional" data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components "below" them in the tree. - A component may choose to pass its state down as props to its child components: E.g. <FormattedDate date={this.state.date} /> - Analogy: If you imagine a component tree as a waterfall of props, each component's state is like an additional water source that joins it at an arbitrary point but also flows down.
What is the Effect hook (useEffect)?
- The Effect Hook lets you perform side effects in function components. **you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined. By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we'll refer to it as our "effect"), and call it later after performing the DOM updates. E.g. // Similar to componentDidMount and componentDidUpdate: useEffect(() => { // Update the document title using the browser API document.title = `You clicked ${count} times`; });
What does "componentDidMount( ) " do? What's its utility?
- The componentDidMount() method runs after the component output has been rendered to the DOM. E.g. This is a good place to set up a timer: componentDidMount() { this.timerID = setInterval( () => this.tick(), 1000 ); }
What is a constructor( ) method, and why would we use it in a Class Component in React.js?
- The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method. A constructor can use the super keyword to call the constructor of the super class. - in React.js, we can initialize state in a Class Component
What do we pass to useState as an argument?
- The only argument to the useState() Hook is the initial state. Unlike with classes, the state doesn't have to be an object. We can keep a number or a string if that's all we need.
Does useEffect run after every render?
- Yes! By default, it runs both after the first render and after every update. Instead of thinking in terms of "mounting" and "updating", you might find it easier to think that effects happen "after render". React guarantees the DOM has been updated by the time it runs the effects.
How would you use *Default Props*? What is a default prop?
- You can assign default props to a component as a property on the component itself and React assigns the default prop if necessary. This allows you to specify what a prop value should be if no value is explicitly provided. e.g. MyComponent.defaultProps = { location: 'San Francisco' } - you have defined a location prop that's set to the string San Francisco, unless you specify otherwise.
Can you give an example of useEffect( )?
- import React, { useState, useEffect } from 'react'; function Example() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }); return ( <div> <p>You clicked {count} times</p>
How do we "share" state in React.js?
- sharing state is accomplished by moving it up to the closest common ancestor of the components that need it -> called "lifting state up". By doing so, we ensure that children components will have the same state since they are retrieving data from the same place
What is the 'useState' hook for?
- useState is a Hook that lets you add React state to function components; it declares a "state variable". This is a way to "preserve" some values between the function calls — useState is a new way to use the exact same capabilities that this.state provides in a class. You can use it within functional components like so: function Example() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0);
Are React events camelCase?
- yes - Eg.
How can we set state in a React.js class component?
- you can use setState ( ) E.g. In a method called tick ( ) : //we use this.setState( ) to set the date key in the object to a new value generated by new Date ( ) tick( ) { this.setState({ date: new Date() }); }
How would you pass an array as props?
<ParentComponent> <ChildComponent colors={["green", "blue", "red"]} /> </ParentComponent>
Why are JSX components useful? (*Hint: Think of HTML)
Because a JSX component represents HTML, you could put several components together to create a more complex HTML page. This is one of the key advantages of the component architecture React provides. It allows you to compose your UI from many separate, isolated components. This makes it easier to build and maintain complex user interfaces.
Why should you think of your U.I. in terms of components when working with React?
Component composition is one of React's powerful features. When you work with React, it is important to start thinking about your user interface in terms of components like the App example in the last challenge. You break down your UI into its basic building blocks, and those pieces become the components. This helps to separate the code responsible for the UI from the code responsible for handling your application logic. It can greatly simplify the development and maintenance of complex projects.
What is React?
Created by Facebook. Open-source JS library for building U.I. Used to create components, handle state & props, utilize event listeners & life cycle methods to update data as it changes
How would you compose components together? (**Think Parent & child components)
E.g. Imagine you are building an App and have created three components, a Navbar, Dashboard, and Footer. return ( <App> <Navbar /> <Dashboard /> <Footer /> </App> ) - To compose these components together, you could create an App parent component which renders each of these three components as children. To render a component as a child in a React component, you include the component name written as a custom HTML tag in the JSX. - When React encounters a custom HTML tag that references another component (a component name wrapped in < /> like in this example), it renders the markup for that component in the location of the tag. This should illustrate the parent/child relationship between the App component and the Navbar, Dashboard, and Footer.
What do you need to grab the id for a target node when rendering a React component?
E.g. ReactDOM.render(<TypesOfFood/>, document.getElementById('challenge-node') ); Answer: document.getElementById( )
How would I pass in a React component into ReactDOM.render( ) ?
For JSX elements, you pass in the name of the element that you want to render. However, for React components, you need to use the same syntax as if you were rendering a nested component, for example : ReactDOM.render(<ComponentToRender />, targetNode). You use this syntax for both ES6 class components and functional components.
Are JSX self-closing tags the same as HTML self-closing tags?
In JSX, the rules are a little different. Any JSX element can be written with a self-closing tag, and every element must be closed. The line-break tag, for example, must always be written as <br /> in order to be valid JSX that can be transpiled. A <div>, on the other hand, can be written as <div /> or <div></div>. The difference is that in the first syntax version there is no way to include anything in the <div />.
What are React props?
In React, you can pass props, or properties, to child components. Say you have an App component which renders a child component called Welcome which is a stateless functional component. You can pass Welcome a user property by writing: EG. <App> <Welcome user='Mark' /> </App> You use custom HTML attributes created by you and supported by React to be passed to the component. In this case, the created property user is passed to the component Welcome. Since Welcome is a stateless functional component, it has access to this value like so: EG. const Welcome = (props) => <h1>Hello, {props.user}!</h1> - It is standard to call this value props and when dealing with stateless functional components, you basically consider it as an argument to a function which returns JSX. You can access the value of the argument in the function body.
Is React HTML? Or JS?
It combines HTML & JS functionality to create its own markup language, JSX.
Is JSX valid JavaScript?
It is NOT. JSX code must be compiled into JavaScript. The transpiler, Babel is typically used for this.
What does useState return?
It returns a pair of values: the current state and a function that updates it. This is why we write const [count, setCount] = useState(). This is similar to this.state.count and this.setState in a class, except you get them in a pair.
Are there any differences as to how to render ES6 components versus simple components?
NOPE! You can render JSX elements, stateless functional components, and ES6 class components within other components.
Does JSX have to return a single element?
One important thing to know about nested JSX is that it must return a single element. This one parent element would wrap all of the other levels of nested elements. For instance, several JSX elements written as siblings with no parent wrapper element will not transpile. - EG. Valid JSX -> <div> <p>Paragraph One</p> <p>Paragraph Two</p> <p>Paragraph Three</p> </div>
What is JSX?
React uses a syntax extension of JavaScript called JSX that allows you to write HTML directly within JS. Lets you used the full programmatic power of JS within HTML, and keeps code readable. - because JSX is a syntactic extension of JavaScript, you can actually write JavaScript directly within JSX. To do this, you simply include the code you want to be treated as JavaScript within curly braces: { 'this is treated as JavaScript code' }
When do we use ReactDOM.render( )???
ReactDOM.render( ) must be called after the JSX element declarations, just like how you must declare variables before using them