All Coursera Quiz Answers

Final graded quiz: Advanced React Quiz Answers

In this article i am gone to share Coursera Course: Advanced React by Meta Week 4 | Final graded quiz: Advanced React Quiz Answers with you..

Enroll Link: Advanced React

Advanced React Coursera Quiz Answers


Also visit this link:ย  Module quiz: JSX and Testing Quiz Answers


 

Final graded quiz: Advanced React Quiz Answers

Question 1)
You are building a form using both Formik and Yup libraries, where one of the inputs is an email. Here are this inputโ€™s client validation rules:

  1. It has to be a valid email address.
  2. If the email input is invalid, a message โ€œInvalid email addressโ€ will be displayed.
  3. If the email input is blank, a message โ€œRequiredโ€ will be shown.

Based on the above requirements, choose the correct Yup validation code from the provided options.

  • Yup.email(“Invalid email address”).required(“Required”).
  • Yup.email().string(“Invalid email address”).required(“Required”)
  • Yup.string().email(“Invalid email address”).required(“Required”)

 

Question 2)
You have the following React application where you have a ToDo component that has 2 text labels and an uncontrolled text input and the entry point App component that renders a list of two ToDos and a button to reverse the order of the ToDos. To avoid a React keys warning, a key is provided to each ToDo component, with the index as its value. Suppose that the next sequence of events happen in the application:

1. You write โ€œDo laundryโ€ in the first ToDo input
2. You write โ€œGo shoppingโ€ in the second ToDo input
3. You click the button to reverse the order

What would happen on the screen after that?

const ToDo = props => (
    <tr>
        <td>
            <label>{props.id}</label>
        </td>
        <td>
            <input />
        </td>
        <td>
            <label>{props.createdAt}</label>
        </td>
    </tr>
);


function App() {
    const [todos, setTodos] = useState([
        {
            id: 'todo1',
            createdAt: '18:00',
        }, 
        {
            id: 'todo2',
            createdAt: '20:30',
        }
    ]);

    const reverseOrder = () => {
        // Reverse is a mutative operation, so we need to create a new array first.
        setTodos([...todos].reverse());
    };

    return (
        <div>
            <button onClick={reverseOrder}>Reverse</button>
            {todos.map((todo, index) => (
                <ToDo key={index} id={todo.id} createdAt={todo.createdAt} />
            ))}
        </div>
    );
}

 

  • todo2 Do laundry 20:30
    todo1 Go shopping 18:00
  • todo1 Go shopping 18:00
    todo2 Do laundry 20:30
  • todo2 Go shopping 20:30
    todo1 Do laundry 18:00

 

Question 3)
True or false: There are at least two errors in the code below.

import{ createContext, useContext, useState} from"react";

const ThemeContext = createContext(undefined);

export const ThemeProvider= () => {
    const[theme, setTheme] = useState("light");

    return(
        <ThemeContext.Provider
            value={{
                theme,
                toggleTheme: () => setTheme(!theme),
            }}
        >
        </ThemeContext.Provider>
    );
};

 

  • True
  • False

 

Question 4)
Select all the statements that are true for React elements:

  • Each element object should have at least two properties: type and children
  • The type of an element can be a DOM node, like a HTML button.
  • The type of an element can be a function corresponding to a React component, like a SubmitButton.
  • A tree of elements can mix and match both components and DOM elements as the type property.

 

Question 5)
True or false: When the user clicks the Submit button, the โ€œWithClickโ€ string will never be output to the console.

const Button = ({ children, ...rest }) => (
    <button onClick={() => console.log("ButtonClick")} {...rest}>
        {children}
    </button>
);

const withClick = (Component) => {
    const handleClick = () => {
        console.log("WithClick");
    };

    return(props) => {
        return<Component {...props} onClick={handleClick} />;
    };
};

const MyButton = withClick(Button);

export default function App() {
    return <MyButton onClick={() => console.log("AppClick")}>Submit</MyButton>;
}

 

  • True
  • False

 

Question 6)
When writing a test for a React component using jest and react-testing-library, how would you assert that a function has been called with some specific arguments?

  • Using the toHaveBeenCalled matcher.
  • Using the toHaveAttribute matcher.
  • Using the toHaveBeenCalledWith matcher.

 

Question 7)
True or false: The following piece of code is an example of the render props pattern.

<LoginUser renderUser={<p>Mark</p>} />

 

  • True
  • False

 

Question 8)
What do you need to add to this code to make the useEffect run only once?

React.useEffect(()=> {
    console.log('The value of the person variable is', person)
})

 

  • Add an empty dependency array.
  • Move the console.log outside of the arrow function
  • Move the console.log outside of the useEffect function

 

Question 9)
You are given the below piece of code.

import {useState} from "react";

export default function App() {
const [restaurantName, setRestaurantName] = useState("Lemon");

function updateRestaurantName() {
setRestaurantName("Little Lemon");
};

return (

 

True or false: The restaurantName variable’s value will always be reset between re-renders of the App component.

  • True
  • False

 

Question 10)
The below code is not valid, because:

if (data !== '') {
    useEffect(() => {
        setData('test data');
    });
}

 

  • You’re breaking the rules of hooks.
  • You’re using the if statement wrong.
  • You’re using the arrow function wrong.
  • There’s a typo in the arrow function.

 


 

Question 11)
A team is tasked with implementing a ThemeProvider for an application that will inject into the tree a light/dark theme, as well as a toggler function to be able to change it. For that, the following solution code has been incorporated. However, unwittingly, some errors have been introduced that prevent it from working correctly. What are the errors in the code solution? Select all that apply.

import{ createContext, useContext, useState} from"react"; 
const ThemeContext = createContext(undefined); 
export const ThemeProvider= () => { 
const[theme, setTheme] = useState("light"); 
return( <ThemeContext.Provider 
value={{ 
theme, 
toggleTheme: () => setTheme(!theme), 
}} > 
</ThemeContext.Provider> );};
  • The toggleTheme implementation is incorrect.
  • The children are not passed through
  • The default value of createContext should be โ€œlightโ€ instead of undefined.
  • There is no need to use local state for the context.

 

Question 12)
True or False: The type of a React element can be a DOM node, such as, for example, an HTML button.

  • True
  • False.

 

Question 13)
True or false: When the Submit button is clicked, the code below will output the words โ€œWithClickโ€ to the console.

const Button = ({ children, ...rest }) => 
( <button onClick={() => console.log("ButtonClick")} {...rest}> 
{children} </button> ); const withClick = (Component) => 
{ const handleClick = () => { console.log("WithClick"); };

 

  • True
  • False

 

Question 14)
Is the following piece of code a valid implementation of the render props pattern?

<MealProvider render={data => (
<p>Ingredients: {data.ingredients}</p>
)}/>
  • Yes
  • No

 

Question 15)
Is the following code snippet valid? Why?

if (data !== '') {
useEffect(() => {
setData('test data');
});
}
  • It’s not valid, because it’s breaking the rules of hooks.
  • It’s valid, because it’s not breaking the rules of hooks.
  • It’s valid, because you can use the useEffect() call in an if statement.

 

Question 16)
You are building a form using both Formik and Yup libraries, where one of the inputs is an email. Before the form gets submitted to the server, you would like to set up some client validation with Yup to make sure the field has an email that is valid, otherwise a message โ€œInvalid email addressโ€ would be shown on the screen. The submit button will be disabled if no email is provided at all. If the email field is empty, the message โ€œRequiredโ€ will be shown on the screen. Given those requirements, how would you write the validation rule using the Yup library?

  • Yup.email().string(“Invalid email address”).required(“Required”)
  • Yup.email(“Invalid email address”).required(“Required”)
  • Yup.string().email(“Invalid email address”).required(“Required”)

 

Question 17)
You have the following React application where you have a ToDo component that has two text labels and an uncontrolled text input and the entry point App component that renders a list of two ToDos and a button to reverse the order of the ToDos. To avoid a React keys warning, a key is provided to each ToDo component, with the index as its value. Suppose that the next sequence of events happen in the application:

1. You write โ€œWash the carโ€ in the first ToDo input
2. You write โ€œBuy bumper stickersโ€ in the second ToDo input
3. You click the button to reverse the order

What would happen on the screen after that?

const ToDo = props => (
    <tr>
        <td>
            <label>{props.id}</label>
        </td>
        <td>
            <input />
        </td>
        <td>
            <label>{props.createdAt}</label>
        </td>
    </tr>
);

function App() {
    const [todos, setTodos] = useState([
        {
            id: 'todo1',
            createdAt: '18:00',
        }, 
        {
            id: 'todo2',
            createdAt: '20:30',
        }
    ]);

    const reverseOrder = () => {
        // Reverse is a mutative operation, so we need to create a new array first.
        setTodos([...todos].reverse());
    };

    return (
        <div>
            <button onClick={reverseOrder}>Reverse</button>
            {todos.map((todo, index) => (
                <ToDo key={index} id={todo.id} createdAt={todo.createdAt} />
            ))}
        </div>
    );
}

 

  • todo2 Wash the car 20:30
    todo1 Buy bumper stickers 18:00
  • todo1 Buy bumper stickers 18:00
    todo2 Wash the car 20:30
  • todo2 Buy bumper stickers 20:30
    todo1 Wash the car 18:00

 

Question 18)
Consider the code below, and choose the correct sentence about this code.

import{ createContext, useContext, useState} from"react";

const ThemeContext = createContext(undefined);

export const ThemeProvider= () => {
    const[theme, setTheme] = useState("light");

    return(
        <ThemeContext.Provider
            value={{
                theme,
                toggleTheme: () => setTheme(!theme),
            }}
        >
        </ThemeContext.Provider>
    );
};

 

  • This code has one or more errors in it, and thus needs to be fixed.
  • This code doesnโ€™t have an error and can be ran as is, without errors.

 

Question 19)
Assuming you have the following set of components, what would be logged into the console when clicking the Submit button that gets rendered on the screen?

const Button = ({ children, ...rest }) => (
    <button onClick={() => console.log("ButtonClick")} {...rest}>
        {children}
    </button>
);

const withClick = (Component) => {
    const handleClick = () => {
        console.log("WithClick");
    };

    return(props) => {
        return<Component {...props} onClick={handleClick} />;
    };
};

const MyButton = withClick(Button);

export default function App() {
    return <MyButton onClick={() => console.log("AppClick")}>Submit</MyButton>;
}

 

  • โ€œButtonClickโ€.
  • โ€œWithClickโ€
  • โ€œAppClickโ€

 

Question 20)
True or False: Using jest and react-testing-library, to assert that a function has been called with some specific arguments, you would need to use the toHaveAttribute matcher.

  • True.
  • False.

 

Question 21)
Among the following code examples, what are valid implementations of the render props pattern?

  • <MealProvider render={data => (
    <p>Ingredients: {data.ingredients}</p>
    )} />
  • <Row renderIcon={() => <Icon name=โ€addโ€ />} />
  • <LoginUser renderUser={<p>Mark</p>} />

 

Question 22)
Inspect the given code snippet.

React.useEffect(()=> {
console.log('The initial value of the price variable is', price)
})

Where should you add an empty array to have the effect ran only on initial render?

  • As a second argument of the arrow function passed to the useEffect() call.
  • You need to add an empty array in a separate arrow function.
  • You can’t add an empty array in this code snippet.

 

Question 23)
True or false? In the following component, the setRestaurantName variableโ€™s value will not be reset between re-renders of the App component.

import {useState} from "react";

export default function App() {
    const [restaurantName, setRestaurantName] = useState("Lemon");

    function updateRestaurantName() {
        setRestaurantName("Little Lemon");
    };

    return (
        <div>
            <h1>{restaurantName}</h1>
            <button onClick={updateRestaurantName}>
                Update restaurant name
            </button>
        </div>
    );
};

 

  • True
  • False

 

Question 24)
Is this valid code?

if (data !== '') {
useEffect(() => {
setData('test data');
});
}
  • No
  • Yes

 

Question 25)
True or False: A tree of elements cannot mix and match both components and DOM elements as the type property.

  • True
  • False

 

Question 26)
You are building a form using both Formik and Yup libraries, where one of the inputs is an email. Before the form gets submitted to the server, you would like to set up some client validation with Yup to make sure the field has an email that is valid, otherwise a message โ€œInvalid email addressโ€ would be shown on the screen. This field is also required. Choose the correct validation code from the three code snippets.

  • Yup.email().string(“Invalid email address”).required(“Required”)
  • Yup.email(“Invalid email address”).required(“Required”)
  • Yup.string().email(“Invalid email address”).required(“Required”)

 

Question 27)
You need the below code snippet to run only after the initial render. What updates (if any) do you need to make to the code?

React.useEffect(()=> {
console.log('The value of the toggle variable is', toggle)
})
  • Add an empty dependency array.
  • You shouldn’t make any updates.
  • You should remove the toggle variable.