What is a virtual DOM?
The Virtual DOM is an in-memory tree representation of the browser's Document Object Model. React's philosophy is to interact with the Virtual DOM instead of the regular DOM for developer ease and performance.
How does the virtual DOM and the DOM interact?
By trading off the additional memory requirements of the Virtual DOM, React is able to optimize for efficient subtree comparisons, resulting in fewer, simpler updates to the less efficient DOM.
What is the upside to the additional memory requirements using the virtual DOM?
By trading off the additional memory requirements of the Virtual DOM, React is able to optimize for efficient subtree comparisons, resulting in fewer, simpler updates to the less efficient DOM.
The result of these tradeoffs is improved performance.
What is a key aspect of the React philosophy?
Thinking about how the UI should look at any given moment, rather than how to change it over time, eliminates a whole class of bugs.
How is every virtual DOM node eventually constructed?
Eventually every virtual DOM note is constructed using the React.createElement function.
How many arguments does the React.createElement function take?
Create the following structure using React.createElement:
<ul>
<li class='selected'>
<a href='/pets'>Pets</a>
</li>
<li>
<a href='/owners'>Owners</a>
</li>
</ul>
React.createElement(
'ul',
null,
React.createElement(
'li',
{ className: 'selected' },
React.createElement('a', { href: '/pets' }, 'Pets' ),
),
React.createElement(
'li',
null,
React.createElement('a', { href: '/owners' }, 'Owners' ),
),
);
How do you render an object with React?
ReactDOM.render(
component, //The react component to rendertarget // the browser DOM node to render it to
);
Using react, render the component named App to the DOM node 'root'
ReactDOM.render(
<App />,
document.getElementById('root')
);
Render the same element as above, using strict mode
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
How would you construct virtual DOM nodes using HTML-like syntax?
Using JSX
What is JSX?
JSX is a special format to let you construct virtual DOM nodes using familiar HTML-like syntax. You can put the JSX directly into your .js files, however you must run the JSX through a pre-compiler like Babel in order for the browser to understand it.
What do you need to use in order for the browser to understand JSX?
Using Bable, the JSX code is compiled to a series of recursively nested createElement calls, rather than <elt> JSX syntax.
You're given an array of cards containing name, imgUrl, and content. What are the 3 steps you need to take to render these cards?
const rootDiv = document.getElementById("root");
const cards = [
{
name: "Martok",
imgUrl: "http://guide.fleetops.net/images/avatars/martok.png",
content: "Ferocious Klingon"
},
{ name: "Mijural",
imgUrl: "http://guide.fleetops.net/images/avatars/mijural.png",
content: "Shrike Class Romulan"
}
]
ReactDOM.render(
<StarTrekCardDeck cards={cards} />,
rootDiv
)
const StarTrekCardDeck = (props) => {
return (
<div>
//Here we are mapping the cards into <StarTrekCard> components
{props.cards.map(card =>
<StarTrekCard
imgUrl={card.imgUrl}
content={card.content}
key={card.name} />
)}
</div>
);
}
const StarTrekCard = (props) => {
return (
<div className="card">
<div className="card-image">
<figure className="image">
<img src={props.imgUrl} />
</figure>
<div className="card-content">
<div className="content">
{props.content}
</div>
</div>
</div>
);
}
What is the command to create a React project named "my-app-name"?
npx create-react-app my-app-name
Name the two folders that have files we don't typically needd:
Name the files in the public folder that we don't need
public folder:
Name the files in the src folder we don't need
src folder:
What files do you need to modify after deleting the files from public and src?
Any files that reference the deleted files.
Also, index.html can be replace with a boilerplate HTML file.
When you modify index HTML to the boilerplate file, what do you need to remember to do?
Add a div with an id of 'root' you will use in your ReactDOM.render() call;
How would you create a custom react app from aA's custom template?
npx create-react-app my-app-name --template @appacademy/simple
Using ES2015 class syntax, describe the file contents if the class is named "Hello"
You need to import React, extend the class using React.Component, use the render() {} function, and export default Hello;
import React from 'react'
class Hello extends React.Component {
constructor() {
super();
this.state = {
name: this.pickRandomName();
}
}
pickRandomName() {
const randomNum = Math.floor(Math.random() * 3);
const names = ['LeBron', 'Messi', 'Serena']
return names[randomNum];
}
changeName = () > {
this.setState({
name: this.pickRandomName()
});
}
render() {
return (
<>
<h1j>Hello {this.state.name}!</h1>
<button onClick={this.changeName}>Change name</button>
</>
)
}
}
export default Hello;
How would you initialize a state within a class component?
class
Where should you NOT update state?
Any instance method except for render()
How would you update the state of an email address entered in your form?
handleEmail = (e) > {
this.setState({
email: e.target.value
});
}
How would you provide default values for a class component's props?
Place this right before your export:
Books.defaultProps = {
books: [
{title: "Don Quixote", author: "Miguel De Cervantes"},
{title: "Pedro Paramo", author: "Juan Rulfo"}|
]
};
In a form, how would you add event listeners?
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.value}/>
<button>Submit!</button>
</form>
)
}
How do you prevent event default behavior?
handleSubmit = e > {
e.preventDefault();
const inputVal = this.state.value;
}
Can you pass a function through props?
Yes!
How would you call the function passed through props?
this.props.submitForm(inputVal)
What are two ways we can safely use "this" keyword within event handlers?
changeEmail = e =>{
this.setState({
email: e.target.value
});
constructor() {
super();
this.state = { email: ''};
this.changeEmail = this.changeEmail.bind(this);
}
Describe what the React SyntheticEvent object is?
The SyntheticEvent object mimics the characteristics of the event passed to the callback in an event handler but adding more data to it.
What is a Synthetic Event?
Your event handlers will be passed instances of SyntheticEvent, a cross-browser wrapper around the browser's native event. It has the same interface as the browser's native event, except the events work identically across all browsers.
What are two of the interfaces SyntheticEvent provides similar to your browser's native event?
stopPropagation()
and preventDefault()
Create a React class component containing a form with one input area, a button named "Submit", a submit callback named handleSubmit, and a callback on the input the sets the value and calls handleResponse when the value of the input box changes.
class Simpleform extends React.Component { constructor() { super(); this.state = { response: '' } } handleResponse = e => { this.setState({ response: e.target.value }); } handleSubmit = e => { e.preventDefault(); this.props.submitForm(this.state.response); } render() { return ( <form onSubmit={this.handleSubmit}> <input onChange={this.handleResponse} type="text" value={this.state.response} /> <button>Submit</button> </form> ); } }
Define a single event handler method to handle onChange events for multiple "input" elements.
onChange = (e) => {
const { name, value } = e.target;
this.setState( { [name]: value });
}
render() {
return(
<form onSubmit={this.onSubmit}>
<input
onChange={this.onChange}
name='email'
type="text"
value{this.state.email}
/>
<input
onChange={this.onChange}
name='password'
type='text'
value={this.state.password}
/>
<button>Submit</button>
</form>
);
}
Add a "textarea" element to a form
The textarea element in React uses a value attribute instead of inner content. It is handled the same way you would handle an input element. It will be a self-closing tag;
Normal html:
<textarea>This is the text that goes in the text area.</textarea>
However, in React, the text goes in a value attribute, and the element is self-closing
<textarea value={this.state.text} onChange={this.onChange} />
How do you write a select element on a form?
<select name='timezone' onChange={this.onChange} value={this.state.timezone}>
<option>PST</option>
<option>CST</option>
<option>EST</option>
</select>
What steps might you take to validate input?
validate(spiritAnimal) {
const validationErrors = [];
if (!spiritAnimal) {
validationErrors.push('Please provide a spirit animal');
}
return validationErrors;
}
onSubmit = e => {
e.preventDefault();
const { spiritAnimal } = this.state;
const validationErrors = this.validate(spiritAnimal);
if (validationErrors.length > 0) {
this.setState( {validationErrors});
} else {
this.props.submitForm(spiritAnimal);
this.setState({spiritAnimal: ''});
}
}
Describe the lifecycle of a React component
Describe the steps when the React component is added to the virtual DOM:
Describe the events when a React component is updated.
When does the componentWillUnmount method get called?
Just before a React component gets removed from the virtual DOM.
Should you fetch data from within the constructor?
No! Use componentDidMount instead.
How would you fetch data?
Use the componentDidMount() lifecycle event.
componentDidMount() {
fetch(url)
.then(response => response.json())
.then(data => this.setState( { movieInfo: data} ));
}
What steps do you need to take to use the react router?
npm install --save react-router-dom@^5.1.2
import { BrowserRouter } from 'react-router-dom';
How many child components can BrowserRouter have?
Only ONE
How do you circumvent the constraint on child components for BrowserRouter?
Use a div tag to surround your components to be controlled by the Router, including the Route tag
import { BrowserRouter } from 'react-router-dom';
const App = () => {
return (
<BrowserRouter>
<div> //Note that BrowserRouter can only have a single child Component!
//Include components here you want to be controlled by the Router, including
//the <Route> tag
</div>
</ BrowserRouter>
);
};
What arguments does a <Route>
component take?
:
character.
<Route path='/users/:userId' />
<Route path='/users/:userId/stores/:storyId'/>
history
location
and match
properties. /users/1
this will render the Component UserProfile
:
<Route path='/users/:userId' component={UserProfile} />
component
this will cause a component to render, you can pass this an arrow function that renders multiple components. Usually we use this so we can pass custom props to the component. Using the component
tag doesn't let us do this.In your route, suppose you want to pass an extra prop called "token" to the user Profile page. How would you do this?
We can do it but we need to pass the regular props from <Route>
as well by using the spread operator: {...props}
.
<Route
path='/users/:userId'
render={props => <UserProfile {...props} token={token} }/>
What package would you need to generate navigation links?
npm install react-router-dom
then include it by require Router from 'react-router-dom';
What does Link
render?
Link
renders an anchor tag <a href=""></a>
that when clicked, changes the window.location.href
to the url
What happens when you click on a simple Link
anchor tag?
Clicking on the a href link triggers BrowserRouter
to parse the url and look for matching <Route>
components.
How would you write a simple Link
element?
<Link to="/">App</Link>
<Link to="/users">Users</Link>
<Link to="/users/1">Andrew's Profile</Link>
What's the difference between the <Link>
element and the <NavLink> element?
They're identical except that <NavLink>
has a optional activeClassName
and activeStyle
props that will set a css class or css styles
<NavLink to="/">App</NavLink>
<NavLink activeClassName="red" to="/users">Users</NavLink>
<NavLink activeClassName="blue" to="/hello">Hello</NavLink>
<NavLink activeClassName="green" to="/users/1">Andrew's Profile</NavLink>
<NavLink to="/" onClick={handleClick}>App with click handler</NavLink>
By default, what does React Router Match for the url '/'?
<Route path='/' ... >
<Route path='/users' ... >
<Route path='/users/:userId' ...>
All of these routes!
What two ways can you make the <Route> match exact paths?
exact
keyword<Switch>
component. How many <Route>
elements will match inside a switch component?
Only one of the routes inside the component to be rendered at any given time.
Remember: the first route to match in a <Switch>
is the winner!
<Switch>
<Route path="/users/:userId" component={ (props) => <Profile ujsers={users} {...props} />} />
<Route exact path="/users" render={() => <Users users={users} />} />
<Route path="/hello" render={ () => <h1>Hello!</h1>} />
<Route exact path="/" component={App} />
<Route render={ (J) => <h1>404: Page not found</h1>} />
</Switch>
How would you access the router properties when you're inside a component?
Use the React Router match prop to access router parameters.
Given the following <Route>
:
<Route path='/users/:userId/stories/:storyId' component={UserStories}/>
If the url were /users/1/stories/2
then the props.match.params
inside of UserStories
would look like:
console.log(props.match.params);
// Will log this:
// {
// userId: 1,
// storyId: 2
// }
How would you redirect your component to another url?
Use the props.history
prop that <Route>
sends to your component.
const redirect = () => this.props.history.replace('/some/other/url');
How would you enable the user to push the Back button in the browser to go back to the previous url?
Use the props.history
function that <Route>
sends to your component.
const handleClick = () => this.props.history.push('/some/url');
This pushes a new URL (and adds to the end of the history stack);
If you use the <Route>
history prop, and replace a url, what will the resulting history stack look like?
Using this.props.history.replace('/some/other/url')
will replace the current URL, but it won't be tracked in the history stack.
How would you redirect a user to a different URL, like for instance after they've logged in?
Use the <Redirect> component
<Redirect to="/">
What is a nested route?
A nexted route is when we use a <Route>
component inside a component that hasn't been rendered yet instead of creating them in your top level component directly under <BrowserRouter>
.
Why would you use a nested route?
Nested routes allows us to keep those routes close to the components they render, and it means we are dynamically adding routes on the fly. For instance, if you have a component that renders more routes to their subcomponents, you might use a nested route.
//Destructure 'match' prop
const UserProfile = ( {match: { url, path, params } ) => {
//Custom call to database to fetch a user by a user ID.
const user = fetchUser(params.userId);
const { name, id } = user;
return (
<div>
<h1>Welcome to the profile of {name}!</h1>
{/* Replaced '/users/${id}' URL with 'props.match.url' */}
<Link to={'${url}/posts'}>{name}'s Posts</Link>
<Link to={'${url}/photos'}>{name}'s Photos</Link>
{/* Replaced '/users/:userId' path with 'props.match.path' */}
<Route path={'${path}/posts'} component={UserPosts} />
<Route path={'${path}/photos'} component={UserPhotos} />
</div>}
);
};