Deep Dive Into React Components - Compressed
Deep Dive Into React Components - Compressed
Deep Dive Into React Components - Compressed
Components
Assignment Solutions
Assignment Solutions
Q1. Create a new React class component called UserProfile. This component should receive two props,
username (a string) and email (a string), and display them in a meaningful way within a JSX template.
Ans.
render() {
return (
<div>
<h2>User Profile</h2>
<p>Username: {username}</p>
<p>Email: {email}</p>
</div>
);
Q2. Create a class-based component called Counter with an initial state value of count set to 0. Display the
count value in the component. Implement two buttons, one to increment and one to decrement the count
Ans.
constructor(props) {
super(props);
this.state = {
count: 0,
};
incrementCount = () => {
decrementCount = () => {
render() {
return (
<div>
<h2>Counter</h2>
<p>Count: {this.state.count}</p>
<button onClick={this.incrementCount}>Increment</button>
<button onClick={this.decrementCount}>Decrement</button>
</div>
);
Q3. Build a class-based component called ToggleButton. Initially, the component should display a button
with the text "OFF." When the button is clicked, it should toggle between "ON" and "OFF" each time it's clicked.
Ans.
constructor(props) {
super(props);
this.state = {
isOn: false,
};
toggleState = () => {
render() {
return (
<div>
<h2>ToggleButton</h2>
<button onClick={this.toggleState}>
</button>
</div>
);
Q4. Create a class-based component Todolist that manages a list of tasks. Implement an input field for
adding new tasks, a button to add a task to the list, and a list displaying all tasks. Use state to manage the list
Ans.
constructor(props) {
super(props);
this.state = {
tasks: [],
newTask: '',
};
addTask = () => {
this.setState({
newTask: '',
});
render() {
return (
<div>
<h2>Todo List</h2>
<input
type="text"
value={this.state.newTask}
onChange={this.handleInputChange}
/>
<ul>
<li key={index}>{task}</li>
))}
</ul>
</div>
);
Q5. Develop a class-based component called LoginForm with input fields for "username" and "password."
Implement a form submission handler that logs the entered values to the console when the form is
submitted.
Ans.
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
};
event.preventDefault();
console.log('Username:', this.state.username);
console.log('Password:', this.state.password);
render() {
return (
<div>
<h2>Login Form</h2>
<form onSubmit={this.handleSubmit}>
<div>
<label>Username:</label>
<input
type="text"
name="username"
value={this.state.username}
onChange={this.handleInputChange}
/>
</div>
<div>
<label>Password:</label>
<input
type="password"
name="password"
value={this.state.password}
onChange={this.handleInputChange}
/>
</div>
<button type="submit">Login</button>
</form>
</div>
);