Sunday, March 26, 2023

Upload and display an image using setState in React

 Step 1:Create a state variable for the image file:

 

const [image, setImage] = useState(null);
 

Step 2: Create a function to handle the file input change event:

const handleImageChange = (e) => {
  if (e.target.files[0]) {
    setImage(e.target.files[0]);
  }
};
 

Step 3: In the render method, add an input element to allow the user to select an image file:

<input type="file" onChange={handleImageChange} />
 

Step 4: Add an image element to display the uploaded image:

{image && <img src={URL.createObjectURL(image)} alt="Uploaded Image" />}
 

The URL.createObjectURL method creates a URL for the uploaded image file, which can be used as the src attribute of the img element.

 

Here's the full code:

import React, { useState } from "react";

function ImageUpload() {
  const [image, setImage] = useState(null);

  const handleImageChange = (e) => {
    if (e.target.files[0]) {
      setImage(e.target.files[0]);
    }
  };

  return (
    <div>
      <input type="file" onChange={handleImageChange} />
      {image && <img src={URL.createObjectURL(image)} alt="Uploaded Image" />}
    </div>
  );
}

export default ImageUpload;

Here's the full code After Applying Styles:

 ImageUploader.js

 

 import React, { useState } from "react";
import "../image-uploader/image-uploader.css";

const ImageUploader = () => {
  const [image, setImage] = useState(null);

  const handleImageChange = (e) => {
    if (e.target.files[0]) {
      setImage(e.target.files[0]);
    }
  };

  return (
    <div className="center">
      <div className="form-input">
        <div className="preview">
          {image && (
            <img
              id="file-ip-1-preview"
              src={URL.createObjectURL(image)}
              alt="Uploaded Image"
            />
          )}
        </div>
        <label for="uploadImagesLbl">Upload Image</label>
        <input
          type="file"
          id="uploadImagesLbl"
          accept="image/*"
          onChange={handleImageChange}
        />
      </div>
    </div>
  );
};

export default ImageUploader;

 

image-uploader.css

body {
  margin: 0px;
  height: 100vh;
  background: #1283da;
}
.center {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.form-input {
  width: 350px;
  padding: 20px;
  background: #fff;
  box-shadow: -3px -3px 7px rgba(94, 104, 121, 0.377),
    3px 3px 7px rgba(94, 104, 121, 0.377);
}
.form-input input {
  display: none;
}
.form-input label {
  display: block;
  width: 45%;
  height: 45px;
  margin-left: 25%;
  line-height: 50px;
  text-align: center;
  background: #1172c2;

  color: #fff;
  font-size: 15px;
  font-family: "Open Sans", sans-serif;
  text-transform: Uppercase;
  font-weight: 600;
  border-radius: 5px;
  cursor: pointer;
}

.form-input img {
  width: 100%;

  margin-bottom: 30px;
}

Testing Step 1 :Image Uploader Ui

 

Testing Step 2 :Image Uploader in Action:After Uploading

 

Do's and don'ts for using useState in React

 Here are some do's and don'ts for using useState in React:

Do:

  1. Use useState to manage state in functional components. useState is designed to work specifically with functional components, and is the recommended way to add state to a functional component.

  2. Initialize the state with a default value. When using useState, it's important to provide an initial value for the state. This can be any value, including a boolean, string, number, object, or array.

  3. Use the updater function to update the state. When updating the state, it's important to use the updater function returned by useState rather than modifying the state directly. This ensures that the component re-renders with the updated state.

  4. Use destructuring to access the state and updater function. When using useState, it's common to use destructuring to access the state value and updater function, like this: const [state, setState] = useState(initialState).

Don't:

  1. Modify the state directly. When using useState, it's important not to modify the state directly, as this can cause unexpected behavior in the component.

  2. Use useState in class components. useState is designed to work specifically with functional components, and should not be used in class components. Instead, use the this.state object and this.setState() method to manage state in class components.

  3. Nest useState inside loops or conditional statements. When using useState, it's important not to nest it inside loops or conditional statements, as this can cause unexpected behavior in the component. Instead, use useState at the top level of the functional component.

  4. Overuse useState. While useState is a powerful hook, it's important not to overuse it in your components. If you find that your component has too much state or is becoming difficult to manage, consider breaking it up into smaller, more focused components.

useState Hook in react js

In React, state is used to store data that can change over time, such as user input, API responses, or the current state of a component. In class components, state is managed using the this.state object, but in functional components, the useState hook can be used to add state to the component.

In React, useState is a built-in hook that allows you to add state to functional components. Before hooks were introduced in React, state could only be managed in class components. With useState, you can now use state in functional components as well.

The useState hook takes an initial value as its argument and returns an array with two elements:

  1. The current state value: This is the current value of the state that was passed as the initial value to the useState hook. It is read-only and can be accessed using the array destructuring syntax [state, setState] = useState(initialState).

  2. The state updater function: This is a function that can be called to update the state value. It takes a new value as its argument and re-renders the component with the updated state. The state updater function can be accessed using the array destructuring syntax [state, setState] = useState(initialState).

The useState hook returns an array with two values: the current state value, and a function to update that state value. Here is an example: 

 Example 1:Counter App

import React, { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
 

In this example, we're defining a state variable called count and initializing it to 0 using the useState hook. We're also defining a function called setCount that we can use to update the value of count.

Inside the return statement, we're displaying the current value of count and a button that updates the value of count when clicked.

When the button is clicked, the setCount function is called with a new value for count. React then re-renders the component with the updated value of count.

By using useState, we can easily add state to functional components in React, making it easier to manage the state of our application.

 

Example 2:ON/OFF App

 Here's another example of how to use useState to manage a boolean state value:

import React, { useState } from 'react';

function ToggleButton() {
  const [isOn, setIsOn] = useState(false);

  function handleClick() {
    setIsOn(!isOn);
  }

  return (
    <button onClick={handleClick}>
      {isOn ? 'ON' : 'OFF'}
    </button>
  );
}

In this example, isOn is a boolean state value that is initialized to false using the useState hook. When the user clicks the button, the handleClick function is called, which toggles the value of isOn using the setIsOn function. The component re-renders with the updated state value, causing the button text to change from 'OFF' to 'ON' or vice versa.

Overall, useState is a powerful hook in React that allows you to add state to functional components and manage data that changes over time.


 

 

History of React js

 

React is an open-source JavaScript library for building user interfaces. It was created by Jordan Walke, a software engineer at Facebook, in 2011 as an internal tool to help developers create more efficient and dynamic user interfaces for Facebook's newsfeed.

react js logo

 

React was first introduced to the public at the JSConf conference in May 2013, and it quickly gained popularity within the web development community. In 2015, Facebook released React as an open-source project, allowing developers all over the world to use and contribute to the library.

One of the key features of React is its use of a virtual DOM (Document Object Model), which allows it to efficiently update and re-render only the parts of a web page that need to be changed, rather than re-rendering the entire page. This makes React much faster and more efficient than traditional JavaScript libraries.

React has also gained popularity due to its component-based architecture, which allows developers to build complex user interfaces by breaking them down into smaller, reusable components. This makes it easier to manage code, collaborate on projects, and maintain consistency across different parts of a web application.

Today, React is widely used by developers all over the world, and it has become one of the most popular front-end JavaScript libraries, alongside Angular and Vue.js. It has been used to build some of the most popular websites and web applications, including Facebook, Instagram, Airbnb, Netflix, and many others.

 

Copyright @ 2013 React Tutorials.

Designed by Mathew | mathai