Build Interactive React Components

JavaScriptJavaScriptBeginner
Practice Now

Introduction

In this project, you will learn how to create a simple show/hide functionality using React. You will implement a button that toggles the visibility of an image on the page.

👀 Preview

project preview

🎯 Tasks

In this project, you will learn:

  • How to set up a React project with HTML, CSS, and JavaScript files
  • How to use the useState hook to manage the state of the application
  • How to conditionally render components based on the state
  • How to style the components using CSS

🏆 Achievements

After completing this project, you will be able to:

  • Create a basic React application
  • Implement state management to control the visibility of elements
  • Integrate HTML, CSS, and JavaScript in a React project
  • Understand the fundamentals of building interactive user interfaces with React

Set Up the Project

In this step, you will set up the project and get familiar with the provided files.

  1. Open the editor on the right. You can see the following files in your project directory:
├── style.css
├── index.html
├── script.js
└── dog.png
  1. Click "Go Live" in the bottom right corner to open the project on port 8080.

Implement the Show/Hide Functionality

In this step, you will implement the functionality to show and hide the image using a button.

  1. Open the script.js file.
  2. Create the App component:
function App() {
  const [show, setShow] = React.useState(true);

  return React.createElement(
    React.Fragment,
    null,
    React.createElement(
      "button",
      { onClick: () => setShow(!show) },
      show ? "Hide Element" : "Show Element"
    ),

    show && React.createElement("img", { src: "dog.png" })
  );
}

In this component:

  • We use the useState hook to create a state variable show and a function setShow to update it.
  • The initial value of show is set to true.
  • We render a button that toggles the value of show when clicked.
  • The button text changes based on the value of show.
  • We conditionally render the image using the show state variable.
  1. Save the App.js file.
  2. Refresh the page in your browser.
  3. Click the "Hide Element" button to hide the image.
  4. Click the "Show Element" button to show the image again.
project preview

Congratulations! You have completed the "Show and Hide" project. You have learned how to use React to create a simple show/hide functionality with a button.

✨ Check Solution and Practice

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like