React Test
React Test
React Test
Q1) Here we have class component that updates the state using the input from a form.
state = {
name: "Backbencher",
age: 23,
};
this.setState({
name: e.target.value,
});
};
this.setState({
age: e.target.value,
});
};
render() {
return (
<div>
<form>
<input
type="text"
value={this.state.name}
onChange={this.onNameChange}
/>
<input
type="text"
value={this.state.age}
onChange={this.onAgeChange}
/>
<h2>
</h2>
</form>
</div>
);
Q2) Here is a class component that prints Boom in console whenever it is mounted or updated.
state = {
count: 0,
};
updateState = () => {
this.setState({
count: this.state.count + 1,
});
};
componentDidMount() {
console.log("Boom");
}
componentDidUpdate() {
console.log("Boom");
render() {
return (
<div>
</div>
);
Q3) Here we have a class component with a state value. Each time the button in component is
clicked, the count is incremented.
state = {
count: 0,
};
incrementCount = () => {
this.setState({
count: this.state.count + 1,
});
};
render() {
return (
<div>
</div>
);
function Banner() {
useEffect(() => {
console.log("Count is updated");
});
return (
<div>
<input
type="text"
value={name}
/>
</div>
);
It logs "Count is updated" message even when updating the value in textbox. How can we show the
log message only when the count state is updated?
Q5) What will be the output of the following code?. Explain the reason behind your answer.
<>
<p>{useContext(MyContext)}</p>
<MyContext.Provider value={2}>
<p>{useContext(MyContext)}</p>
</MyContext.Provider>
</>
);
Q6) Which component will be rendered by the following code when navigating to '/login' route ?
Give explanation for your answer.
ReactDOM.render((
<Router>
<div>
</div>
</Router>),
document.getElementById('root')
);
Q7) Study the following piece of code and suggest changes such that only the Profile component is
Rendered when the path is '/dashboard/profile'.
return (<div>App</div>)
return (<div>Dashboard</div>)
}
return (<div>Profile</div>)
return (<BrowserRouter>
</BrowserRouter>
Q9) We have a code snippet from a class component which registers and remove an event listener.
componentDidMount() {
window.addEventListener("mousemove", this.handleMousePosition);
componentWillUnmount() {
window.removeEventListener("mousemove", this.handleMousePosition);
return (
<NameContext.Provider value="Backbencher">
<AgeContext.Provider value="23">
<Test2 />
</AgeContext.Provider>
</NameContext.Provider>
);
function Test2() {
return (
<div>
</div>
Complete Test2 component to consume the context values and display the name and age.