
COURSE 6 – ADVANCED REACT QUIZ ANSWERS
Week 1: Components
Meta Front-End Developer Professional Certificate
Complete Coursera Answers & Study Guide
Click to Enroll in Coursera Meta Front-End Professional Certificate
TABLE OF CONTENT
Components INTRODUCTION
The Meta Front-End Developer Professional Certificate from Coursera is designed to equip you with the foundational knowledge and advanced practical skills necessary to become an expert front-end developer. In this module, you will be assessed on ADVANCED REACT Components, which form a critical part of the professional certificate program. You will learn how to craft reusable React components that can be used in any application.
Additionally, you will develop an understanding of how to work with the core APIs of React to create secure and maintainable applications. Upon successfully completing this module, you should have acquired the necessary skill set to take your development career to the next level.
Learning Objectives
- Render and transform lists with keys in React.
- Distinguish between controlled and uncontrolled React components.
- Create a controlled form component in React.
- Share component state by lifting state up to the closest common ancestor
- Share global state using React Context
SELF-REVIEW: CREATE A BASIC LIST COMPONENT
1. When using the filter operator from arrays in JavaScript, what type should you return from the predicate function to determine if the element should be filtered out or not?
- You should return null if the element should be filtered out and any other value to keep the element.
- You should return true to keep the element and false to filter out the element. (CORRECT)
- You should return undefined to filter out the element and true to keep it in the list.
Correct: That’s correct, the predicate function should always return a boolean, being true to keep the item or false to remove it.
2. When chaining the three array operators required to complete the exercise, map, filter and sort; in which order should they be applied to props.data? Remember that props.data contains an array of dessert objects.
- Sort, filter, map.
- Map, filter, sort.
- Filter, sort, map. (CORRECT)
Correct: That’s correct, filter should go before sort since it returns a new array, making sure a copy of props.data is created before doing the sorting, which is a mutative operation. Map should be always the last, to transform the item into the final React Element that should be rendered.
3. When using the map function to transform an array item into a <li> element, what of the following code snippets should be inside the <li> tag to render the list item correctly in the following format: Ice Cream – 200 cal
- <li>${dessert.name} – ${dessert.calories} cal</li>
- <li>dessert.name – dessert.calories + “cal”</li>
- <li>{dessert.name} – {dessert.calories} cal</li> (CORRECT)
Correct: That’s correct, you should always use curly braces {} to access dynamic data in JSX, without any extra dollar symbol $.
KNOWLEDGE CHECK: RENDERING LISTS IN REACT
1. Imagine you have an array with one object that represents a dessert. You would like to apply some transformation to the item to output a different structure using the map function as per the code below. What would be the value of the newDesserts variable?
const desserts = [ {
title: 'Chocolate Cake',
description: 'Chocolate cake is a cake flavored with melted chocolate',
calories: 500,
}
];
const newDesserts = desserts.map((dessert) => {
return {
title: dessert.title.toUpperCase(),
...dessert,
kCal: dessert.calories / 1000,
};
});
- [ { title: ‘CHOCOLATE CAKE’, description: ‘Chocolate cake is a cake flavored with melted chocolate’, kCal: 0.5, } ]
- [ { title: ‘Chocolate Cake’, description: ‘Chocolate cake is a cake flavored with melted chocolate’, calories: 500, kCal: 0.5, } ] (CORRECT)
- [ { title: ‘CHOCOLATE CAKE’, description: ‘Chocolate cake is a cake flavored with melted chocolate’, calories: 500, kCal: 0.5, }]
Correct: That’s correct, since the mapping output merges the previous object values after the title is re-defined, it has no effect and the title is still as before. Also, a new property is introduced, kCal.
2. How do you access dynamic data inside the JSX from the render function?
- Using local state in the component.
- Using component props.
- Wrapping the variable in question with curly braces. (CORRECT)
Correct: That’s correct, that’s the way to access dynamic data in JSX.
3. What could be a potential problem of using a randomiser function that generates an integer number from 0 to 10 as a key for your list items, having a list of only eight items? Select all that apply
- The randomiser function is a potential performance bottleneck since it has to run every re-render and it’s an unnecessary computation.
- The randomiser function does not entirely guarantee that the keys it generates will be different per item and a collision could happen, having two items with the same integer as keys. (CORRECT)
- There is no persistence of the keys generated since the moment the component re-renders the keys will vary and that could cause unexpected UI changes. (CORRECT)
Correct: That’s correct, since each value generated from the randomiser function is independent of the other, you could have key duplications.
Correct: That’s correct, when a re-render occurs, the randomiser could generate a different value per list item and that could cause issues with the internal state of the component.
4. The todos array contains a list of todo objects, where each object has an id property that is unique. Which of the following code snippets will throw a React warning when opening up the browser console? Select all that apply
{todos.map((todo, index) => ( <ToDo key={index} id={todo.id} />))}
{todos.map((todo, index) => ( <ToDo key={todo.id} id={todo.id} />))}
{todos.map((todo, index) => ( <ToDo id={todo.id} /> ))}
(CORRECT){todos.map((todo, index) => ( <ToDo key=”myKey” id={todo.id} /> ))}
(CORRECT)
Correct: That’s correct, since a key per list item is missing, React will throw a warning in the console.
Correct: That’s correct, the keys are all the same for all items and React will throw a warning in the console regarding that problem.
5. What are the potential problems of using indexes as keys?
- The index is not persisted and will change the moment the component re-renders.
- If the order of items may change, that can negatively impact performance and may cause issues with component state. (CORRECT)
- An index is not guaranteed to be unique.
Correct: That’s correct, indexes are discouraged when the order of the items may change.
SELF-REVIEW: CREATE A REGISTRATION FORM
1. When setting a new value for the password state, that is represented by an object with two properties, value and isTouched, what’s the correct call to the setPassword state setter inside the onChange event handler? Select all that apply.
setPassword({ ...password, value: e.target.value });
(CORRECT)setPassword({ isTouched: false, value: e.target.value });
setPassword({ value: e.target.value });
Correct: That’s correct, isTouched is preserved, since it’s been merged at the beginning in the state setter, before setting the new value.
2. What’s the correct event prop you should use to determine when an input has been interacted with at least once? Select all that apply.
- onFocus
- onBlur (CORRECT)
- onChange
Correct: That’s correct, onBlur fires when the user leaves the focus from a particular input and it’s the best place to set the interaction state to true and provide actionable feedback in the UI if needed.
3. How do you prevent the default behavior of the form HTML tag in React when a submission event occurs?
- By returning false from the onSubmit function prop that the form tag provides.
- By calling preventDefault on the event object inside any onChange handler from an input tag.
- By calling preventDefault on the event object inside the onSubmit function prop from the form tag. (CORRECT)
Correct: That’s correct, that’s the proper way to prevent the default behavior and the right place to perform the call.
KNOWLEDGE CHECK: FORMS IN REACT
1. What of the next input types doesn’t have a controlled version when they are used in React?
<input type=”text” />
<input type=”file” />
(CORRECT)<textarea />
Correct: That’s correct, because its value is read-only, it is an uncontrolled component in React.
2. What are some of the features of controlled components? Select all that apply
- Conditionally disabling the submit button. (CORRECT)
- Enforcing a specific input format. (CORRECT)
- Validating all values in the client side when a submission occurs in the form, before calling the server endpoint. (CORRECT)
Correct: That’s correct, you can specify a condition based on the React state from the different inputs to disable the submit button.
Correct: That’s correct, you can use regular expressions and match the React local state against them to provide instant feedback to users about a specific pattern, like credit cards or phone numbers. Alternatively, you can also control what characters are valid for a specific input and pass them through and ignore invalid ones
Correct: That’s correct, you can access the different input states via React state and perform validation in the submit handler.
3. How do you get the value of an input when its state is handled by the DOM (Uncontrolled)? Select all that apply.
- Using a combination of useEffect and useRef hooks, where a ref is used on the uncontrolled input and then its value can be read on useEffect after a re-render cycle happens.
- Using local state and initializing it to an empty string. Then, reading the input value from the event object when the submission happens and finally setting the local state with that value.
- Using a ref via useRef hook, assigning it to the input and then reading the input value when the submission happens via ref.current.value. (CORRECT)
Correct: That’s correct, that’s the proper way to access the value from an uncontrolled input.
4. What happens when you click on the submit button in the below code snippet?
<form onSubmit={() => alert("Submitting")}>
<input type="text" value={text} onChange={e => setText(e.target.value)} />
<input type="button" value="Submit" />
</form>
- The onSubmit callback is executed and an alert is shown with the text “Submitting”.
- An error is thrown.
- Nothing happens when the button is clicked. (CORRECT)
Correct: That’s correct, the input should be of type submit, otherwise onSubmit callback from the form tag won’t fire.
5. What is missing in the below code for the select component to work properly?
<select onChange={handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
- Each option tag should be accompanied by a label tag.
- Each option tag should have an onChange handler.
- The select tag is missing a value prop. (CORRECT)
Correct: That’s correct, the select tag is missing the current selection via the value prop.
SELF-REVIEW: CREATE A LIGHT-DARK THEME SWITCHER
1. When creating a Provider component, what should you do with the children prop that it receives?
- Nothing, the children prop is not necessary and can be skipped during the rendering.
- You should clone the children inside the component to add the context value to it.
- You should wrap the JSX that it returns with a Context Provider component and then pass the children through. (CORRECT)
Correct: That’s correct, the children should be passed as a direct child of the Context Provider element.
2. Assuming that the default theme for the application is ‘light’, what should be the default value passed to the createContext call? Select all that apply.
- undefined (CORRECT)
- null (CORRECT)
- The string “light” (CORRECT)
Correct: That’s correct, the default value is not relevant and can be any value. It’s only useful for testing components in isolation or as a default value when a context consumer does not have a Provider further up in the tree.
Correct: That’s correct, the default value is not relevant and can be any value. It’s only useful for testing components in isolation or as a default value when a context consumer does not have a Provider further up in the tree.
Correct: That’s correct, the default value is not relevant and can be any value. It’s only useful for testing components in isolation or as a default value when a context consumer does not have a Provider further up in the tree.
3. One of the parts of the context injected into the application is a function called toggleTheme. Assuming that the theme is held in some local state as a string that can be either ‘light’ or ‘dark’. What should be the exact implementation of the toggleTheme function?
toggleTheme: () => setTheme(theme === "light" ? "dark" : "light")
(CORRECT)toggleTheme: (theme) => setTheme(!theme)
toggleTheme: () => setTheme(theme === "light" ? "light" : "dark")
Correct: That’s correct, that’s the right implementation.
KNOWLEDGE CHECK: REACT CONTEXT
1. What of the below scenarios are valid for choosing context instead of local state? Select all that apply.
- The current selection of a group of radio buttons.
- The locale or language that should be used in the application’s text. (CORRECT)
- The visibility state of an alert that overlays into the whole application. (CORRECT)
Correct: That’s correct, since that’s global state that affects all component’s text.
Correct: That’s correct, global alerts are well suited for context since any component can trigger them.
2. What is the problem of props drilling? Select all that apply.
- Components not knowing the local state of their parents.
- Components having to pass down props all the way to the children that need to consume them. (CORRECT)
- Components receiving more props than they should. (CORRECT)
Correct: That’s correct, components drill down props across several levels to reach the children that need them.
Correct: That’s correct, props drilling involves components receiving props that they don’t use or need at all.
3. When creating a new piece of application state, what is the bare minimum of React APIs you would need to define it?
- Context and local state. (CORRECT)
- Context and props.
- Context, props and local state.
Correct: That’s correct, you need local state to define the global state and Context to inject it into a tree.
4. What happens when the value prop of the Context Provider changes?
- All the consumer components re-render with the updated value. (CORRECT)
- The Context Provider component gets recreated.
- The whole component tree under the Context Provider gets re-rendered.
Correct: That’s correct, all components subscribed to that context get updated.
5. What happens when you wrap a component with the React.memo API, such as React.memo(Component). Select all that apply.
- The component never gets updated no matter if there was a change in its local state or the props it receives.
- React provides a performance optimization. (CORRECT)
- Whether the component should re-render could be determined by some custom logic that uses the previous props and the current props. (CORRECT)
Correct: That’s correct, it avoids unnecessary re-renders automatically.
Correct: That’s correct, you can provide an additional function that receives previous props and current props to determine if an update should occur.
Coursera Meta Front-End Developer Professional Certificate Answers and Study Guide
Liking our content? Then don’t forget to ad us to your bookmarks so you can find us easily!
Weekly Breakdown | Meta Study Guides | Back to Top
MODULE QUIZ: COMPONENTS
1. When using a key for your list items, what’s the best general choice?
- Using an ID generated by a library that guarantees no duplications.
- Using an ID coming from the data, that points to the database ID. (CORRECT)
- Using an index.
Correct: That’s correct, that’s the preferred option.
2. Imagine you have a specification for rendering the following list item:
<li>Ice cream - 200 cal</li>
where the name and the number of calories are coming as dynamic data. Select all the options that would correctly render the desired output:
<li>{Ice cream - 200 {item.cal}}</li>
<li>{item.name} - {item.cal} cal</li>
(CORRECT)<li>{`${item.name} - ${item.cal} cal`}</li>
(CORRECT)
Correct: That’s correct, that would render the desired output using JSX syntax.
Correct: That’s correct, that would render the desired output using JSX syntax and string interpolation.
3. Let’s suppose you have a list of two items and a new item is added to the list. From the point of view of the React diffing algorithm, what’s the most optimal position for the new element added? Select all that apply
- The new element added at the beginning.
- The new element added in the 2nd position, in between the existing list items.
- The new element added at the end. (CORRECT)
Correct: That’s correct, that’s the most optimal path.
4. What are controlled components?
- A set of components whose internal state is controlled by the DOM.
- A set of components whose internal state is controlled by React. (CORRECT)
- A set of components whose value is determined by React refs.
Correct: That’s correct, state is delegated from the DOM to React local state.
5. What are the features you can still achieve with uncontrolled components? Select all that apply
- Conditionally disabling the submit button.
- One time value retrieval on submit using a React ref. (CORRECT)
- Validation on submit. (CORRECT)
Correct: That’s correct, the ref allows you to access the internal state held by the DOM.
Correct: That’s correct, in the submit handler function you can use refs to access all the input values and perform any custom client validation.
6. When creating an API for context consumers via useContext, what’s the argument you have to provide to the useContext call?
- The Context.Provider component.
- The Context object obtained via the createContext call. (CORRECT)
- The React state that defines the global state to be injected.
Correct: That’s correct, you always have to pass a context object as argument to the useContext hook.
7. Imagine the below component structure, where all components ComponentA, ComponentB and ComponentC are simple presentational components that hold no props or state:
const App = () => {
return(
<AppContext.Provider>
<ComponentA />
</AppContext.Provider>
);
};
const ComponentA = React.memo(() => <ComponentB />);
const ComponentB = () => <ComponentC />;
const ComponentC = () => null;
- If the App component re-rendered for whatever reason, what would be the sequence of component re-renders that would take place?
- App -> ComponentA -> ComponentB -> ComponentC.
- App -> ComponentB -> ComponentC
- App (CORRECT)
Correct: That’s correct, since ComponentA is wrapped with React.memo, it will prevent unnecessary updates within itself and down the tree, so only the App component would update.
8. Even though props and state are inherently different, what are areas where they overlap? Select all that apply.
- Both props and state are plain JS objects. (CORRECT)
- Both props and state changes trigger a render update. (CORRECT)
- Both props and state are deterministic, meaning that your component always generates the same output for the same combination of props and state. (CORRECT)
Correct: That’s correct, they are both plain JS objects.
Correct: That’s correct, as soon as one or the other update, it will trigger a re-render.
Correct: That’s correct, React components are pure functions when it comes to their rendering output.
9. When defining a JavaScript object as a piece of local React state that will be injected as context, what is the specific React hook that allows you to keep the same object reference in memory and prevent unnecessary re-renders if the object itself hasn’t changed any values?
- UseCallback
- UseMemo (CORRECT)
- useRef
Correct: That’s correct, useMemo keeps in memory the previous object reference and if no changes occur in the object values, it will reuse the same reference on subsequent updates.
10. What are some possible examples of application features that are well suited to be defined as React context? Select all that apply
- The value of a text input.
- The application theme. (CORRECT)
- Locale preferences. (CORRECT)
- The current authenticated user. (CORRECT)
Correct: That’s correct, the theme is one example of global application state.
Correct: That’s correct, local preferences is one example of global application state.
Correct: That’s correct, authenticated user is one example of global application state.
11. Which of the following is true about the map() method in JavaScript. Select all that apply.
- The map() method is a collection of elements.
- The map() method is a transformation operation. (CORRECT)
- The map() method is useful for handling third party data. (CORRECT)
- The map() method returns a new array. (CORRECT)
Correct: That’s correct. The map() method in JavaScript is used to transform lists of data.
Correct: That’s correct. Using the map() method in JavaScript to display data fetched from a third party or external provider differently in your app is a common use case of the map() method.
Correct: That’s correct. When using the map() method, you will need to define a new variable, as it always returns a new array.
12. When you are working with lists in JSX, you can return a React component. What is the purpose of curly braces in this process?
- To access the content of the variable that represents your list item. (CORRECT)
- To store the result of the transformation being performed.
- To access the needed properties from the initial data.
- To loop through the array of initial data.
Correct: That’s correct. When a JSX transformation will be part of the render method of components, you need to use curly braces to wrap your dynamic data so it can be accessed.
13. Which of the following statements about keys in React are true? Select all that apply.
- Keys always positively impact app performance and user interface (UI).
- Keys instruct React about whether a specific element’s internal state should be preserved or not. (CORRECT)
- Keys instruct React how to treat a specific element when an update occurs. (CORRECT)
- Keys help React determine which items have changed, are added or are removed. (CORRECT)
Correct: That’s correct. Amongst other things, keys instruct React on whether a specific element’s internal state should be preserved when updates happen.
Correct: That’s correct. Amongst other things, keys instruct React on how to treat a specific element when updates happen.
Correct: That’s correct. Keys are identifiers that help React determine which items have changed, are added or are removed.
14. True or false: It is recommended to use item indexes as keys when selecting keys for rendered list items.
- False (CORRECT)
- True
Correct: That’s correct. Although item indexes can be used as keys, using indexes as keys can create problems if the order of your list of items is prone to change and can negatively affect performance. Using unique and stable identifiers, such as item IDs, is recommended instead.
15. You are using controlled components in React in order to have more control over the forms in an application you are creating. Which of the following props is used to perform state delegation?
- onChange
- value (CORRECT)
- onSubmit
Correct: That’s correct. State delegation is performed via the value prop. A combination of local state and the value prop is needed to create a controlled component.
16. Imagine you’d like to better control the submission of a form you’re creating for an app.
Which prop is required to prevent the default behavior of the form submit event in React?
- onChange
- preventDefault (CORRECT)
- onSubmit
- value
Correct: That’s correct. To avoid the default form behavior of submitting in React, you must use the event property and call preventDefault.
17. What are the two props you need to add when creating a controlled range component?
- min and max
- htmlFor and id
- range and max
- value and onChange (CORRECT)
Correct: That’s correct. The value prop is used to hook the local state up and onChange prop is used to receive the changes and update the state accordingly
18. Which of the following statements are true about state in React? Select all that apply.
- State is a component’s configuration.
- When designing a component, it must have state.
- State is managed within the component. (CORRECT)
- State is a plain JavaScript object that React uses to hold information. (CORRECT)
- Attributes a component needs to change at some point in time shouldbe part of its state. (CORRECT)
Correct: That’s correct. State is managed within the component, whereas props get passed to the component.
Correct: That’s correct. State and props are both plain JavaScript or JS objects that React uses to hold information.
Correct: That’s correct. If a component needs to alter one of its attributes at somepoint in time, that attribute should be part of its state, otherwise, it should be a prop for that component.
19. Which of the following is true about the Context API? Select all that apply.
- Context requires you to pass props down manually at every level of thecomponent tree.
- Context is the only way to pass data through the component tree.
- Context was introduced by React as a way to resolve the props drillingproblem. (CORRECT)
- Context should be used when you need to share global data. (CORRECT)
Correct: That’s correct. React solved the problem of parent components having to drilldown props all the way to the children that need to consume them byintroducing the Context API.
Correct: That’s true. Context is useful for global state. It is the right tool when you needto share data that can be considered global for a tree of React components.
Components CONCLUSION
In this module, you will be assessed on the key skills covered in the Course. These include your ability to: Understand and explain the main features of effective academic writing; Plan, write and revise an essay or report for an audience using academic conventions; Engage with a range of sources; Present ideas clearly using appropriate language and style for an audience.
If you feel confident that you can demonstrate these skills, then join Coursera now!
Subscribe to our site
Get new content delivered directly to your inbox.
Quiztudy Top Courses
Popular in Coursera
- Meta Marketing Analytics Professional Certificate.
- Google Digital Marketing & E-commerce Professional Certificate.
- Google UX Design Professional Certificate.
- Meta Social Media Marketing Professional Certificate
- Google Project Management Professional Certificate
- Meta Front-End Developer Professional Certificate
Liking our content? Then, don’t forget to ad us to your BOOKMARKS so you can find us easily!