How to add an Image in React

How to add an image in react

Adding images to a React application is a fundamental task when it comes to building engaging and visually appealing user interfaces. Whether you want to display product images, user avatars, or any other graphics, React makes it straightforward to incorporate images into your components.

In this tutorial, we’ll explore various methods and best practices for seamlessly integrating images into your React project. Whether you’re a beginner taking your first steps in React or an experienced developer looking to refine your image-handling skills, this guide will provide you with the knowledge and techniques needed to incorporate images effectively. Let’s dive in and discover how to bring images to life in your React applications.

Certainly, here’s a step-by-step guide on how to add an image in React without relying on AI-generated content:

  1. Prepare Your Image:
    • Start by having your image ready. Ensure that it’s saved in a directory within your React project folder.
  2. Import the Image:
    • In your React component file where you wish to display the image, use the import statement to bring in your image file. You can either use require() or ES6 import syntax.
    • Example using require():
import React from 'react';
import myImage from './path/to/your-image.jpg';
  • Example using ES6 import:
import React from 'react';
import myImage from './path/to/your-image.jpg';
  • Replace './path/to/your-image.jpg' with the actual path to your image file.

3. Render the Image:

  • Within your component’s render method or any JSX part where you intend to display the image, use the <img> HTML element. Set the src attribute to the imported image variable.
  • Example:
render() {
  return (
    <div>
      <h1>My React App</h1>
      <img src={myImage} alt="Description of the image" />
    </div>
  );
}
  • Be sure to include the alt attribute with a meaningful description of the image for accessibility purposes.

4. Optional Styling:

  • If necessary, apply CSS styles to your <img> element to control its appearance, size, alignment, or other visual attributes, just like you would for any HTML element.

Here’s a complete example of how to add an image to a React component:

import React from 'react';
import myImage from './path/to/your-image.jpg';

class MyComponent extends React.Component {
  render() {
    return (
      <div>
        <h1>My React App</h1>
        <img src={myImage} alt="Description of the image" />
      </div>
    );
  }
}

export default MyComponent;

Ensure you replace './path/to/your-image.jpg' with the actual path to your image file. When you build or run your React application, the image will be included and displayed as intended.

This process allows you to seamlessly add images to your React components without AI-generated content.

Let us understand this by an example :

First, we will look at HTML code

<div id="root"></div>
<a target="_blank" title="instagram/web__addict" href="https://www.instagram.com/web__addict/"><i class="fab fa-instagram"></i></a>

Certainly! The provided code snippet contains HTML elements and attributes:

  1. <div id="root"></div>:
  • This is an HTML <div> (division) element with an id attribute set to “root.” The id attribute is used to uniquely identify this <div> element. It’s a common convention in React applications to have a root <div> element with the ID “root.” This element acts as the mounting point for the entire React application’s user interface (UI). React will render its components and content inside this <div>.
  1. <a target="_blank" title="instagram/web__addict" href="https://www.instagram.com/web__addict/">:
  • This is an HTML <a> (anchor) element, which is used to create hyperlinks.
  • target="_blank": This attribute instructs the browser to open the linked URL in a new browser tab or window when clicked. It’s often used for external links to keep the current page open.
  • title="instagram/web__addict": The title attribute provides additional information about the link. In this case, it suggests that the link is related to an Instagram account with the username “web__addict.”
  • href="https://www.instagram.com/web__addict/": The href attribute specifies the URL to which the link points. In this example, it links to the Instagram profile with the username “web__addict.”
  1. <i class="fab fa-instagram"></i>:
  • This is an HTML <i> (italic) element, but it’s commonly used for icons and symbols when combined with CSS classes. Here, it’s used to display an Instagram icon.
  • class="fab fa-instagram": The class attribute assigns CSS classes to the <i> element. These classes are commonly used with icon libraries like FontAwesome. In this case, the classes “fab” and “fa-instagram” are used to style the Instagram icon.

When this code is rendered on a web page, it will display an Instagram icon as a clickable link, and when clicked, it will open the Instagram profile associated with the URL provided in the href attribute. The “root” <div> is typically used in React applications as the entry point where the React application’s UI is rendered.

Now let’s have a look at the CSS code

body{
  font-family: 'Hind Guntur', sans-serif;
  color: #054231;
  display: flex;
  justify-content: center;
  background: #49afa8;
  background-image: url('https://github.com/OlgaKoplik/CodePen/blob/master/leaf.png?raw=true');
  background-repeat: no-repeat, no-repeat;
  background-position:  200% -40%;
  background-size: 80%;
}

.card{
  width: 310px;
  height: 627px;
  padding: 15px;
  margin-top: 40px;
  border-radius: 25px;
  display: flex;
  justify-content: center;
  box-shadow: 15px 10px 25px 0px  #3fa1a9;
  background: #fff;
  background-image: url('https://github.com/OlgaKoplik/CodePen/blob/master/leaf2.png?raw=true'), url('https://github.com/OlgaKoplik/CodePen/blob/master/leaf.png?raw=true');
  background-repeat: no-repeat, no-repeat;
  background-position: 120% -5%, 200% -40%;
  background-size: 40%, 80%;
  animation: open .5s;
}
@keyframes open {
  0%  {background-position: 166% -25%, 220% -69%;}
  100%{background-position: 120% -5%, 200% -40%;}
}
form{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.field{
  margin: 5px;
  display: flex;
  flex-direction: column;
  }
input[type="file"] {
  display: none;
}

.custom-file-upload {
  border-radius: 50%;
  display: inline-block;
  position: relative;
  padding: 6px;
  cursor: pointer;
  background: linear-gradient(270deg, #3fa1a9, #79f1a4);
  margin-bottom: 25px;
}

.img-wrap{
  position: relative;
  width: 200px;
  height: 200px;
  overflow: hidden;
  border-radius: 50%;
}
.img-upload:before{
  content: "\f093";
  font-size: 90px;
  position: absolute;
  padding-top: 80px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #63d3a6;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  opacity: 0;
  transition: .5s ease;
  background-color: #fff;
}
.img-upload:hover:before{
 opacity: 1;
}
img {
  width: auto;
  height: 100%;
}

label{
  text-transform: uppercase;
  font-weight: 700;
  color: #676767;
}

input{
  border-radius: 15px;
  border: 1px solid #b7b7b7;
  padding: 5px 5px 5px 10px;
  font-size: 18px;
  transition: 0.2s;
}
input:focus{
  outline: none;
  border: 1px solid #64d488;
}
input::placeholder{
  color: #bebebe;
}
.name{ 
  text-align: center;
  text-transform: uppercase;
  font-weight: 700;
  color: #676767;
  max-width: 220px;
  overflow-wrap: break-word;
}
.status{
  text-align: center;
  max-width: 220px;
  overflow-wrap: break-word;
}
button{
  position: relative;
  color: #054231;
  letter-spacing: 1px;
  margin: 20px;
  font-size: 18px;
  padding: 10px;
  text-align: center;
  transition: 0.5s;
  border-radius: 10px;
  cursor: pointer;
  border-radius: 25px;
  border: none;
  background: #64d488;
}
.save{
  font-weight: 600;
  left: -20px;
  text-transform: uppercase;
  letter-spacing: 1px;
  width: 20px;
  box-shadow: 20px 0px 40px 0px  #63d3a6;
}
.edit{
  color: #fff;
  width: 180px;
}
button:hover{
  left: 0;
  color: #fff;
  width: 180px;
  box-shadow: 0px 0px 20px 0px  #63d3a6;
}
button:focus{
  outline: none;
}
.lds-ripple {
  display: inline-block;
  position: relative;
  width: 64px;
  height: 64px;
}
.lds-ripple div {
  position: absolute;
  border: 4px solid #fff;
  opacity: 1;
  border-radius: 50%;
  animation: lds-ripple 1s cubic-bezier(0, 0.2, 0.8, 1) infinite;
}
.lds-ripple div:nth-child(2) {
  animation-delay: -0.5s;
}


.fa-instagram{
  position: absolute;
  color: #79f1a4;
  top: 3%;
  right: 2%;
  font-size: 38px;
}
.fa-instagram:hover{
  font-size: 42px;
  color: #caff81;
  transition: all .1s linear;
  cursor: pointer;
}

This CSS code establishes the visual presentation of a webpage. Let’s break down each section:

  1. body: This portion governs the styling of the entire webpage body.
  • font-family: 'Hind Guntur', sans-serif;: Sets the font to “Hind Guntur” for webpage text, with a backup of sans-serif if “Hind Guntur” is unavailable.
  • color: #054231;: Specifies the text color as a shade of green.
  • display: flex; justify-content: center;: Utilizes a flexbox layout to horizontally center content.
  • background: #49afa8;: Establishes a turquoise background color.
  • background-image: url('...');: Adds a background image via a URL.
  • background-repeat: no-repeat, no-repeat;: Prevents the background image from repeating both horizontally and vertically.
  • background-position: ...;: Positions the background image.
  • background-size: ...;: Defines the size of the background image.
  1. .card: This section styles elements with the “card” class, typically used for card-like containers.
  • It sets dimensions, padding, margins, border-radius, and box-shadow to create a card appearance.
  • background-image: url('...'), url('...');: Configures two background images for the card element.
  • background-repeat: no-repeat, no-repeat;: Ensures the background images don’t repeat.
  • background-position: ...;: Adjusts the positions of the background images.
  • background-size: ...;: Specifies the sizes of the background images.
  • animation: Defines an “open” animation with a 0.5-second duration.
  1. form: This part styles form elements within the webpage.
  • It employs flexbox for center-aligning form elements.
  1. .field: These styles are for elements with the “field” class inside the form.
  • It sets margin and applies a flexbox layout to child elements.
  1. input[type="file"]: Styles file input elements to be hidden.
  2. .custom-file-upload: Styles a custom file upload button.
  3. .img-wrap and .img-upload: These styles create a circular image upload container with an icon.
  4. label, input, .name, .status, and button: These styles define various visual attributes for labels, input fields, and buttons, including fonts, colors, borders, and transitions.
  5. .lds-ripple: This class is responsible for a loading animation that generates a ripple effect.
  6. .fa-instagram: These styles govern the appearance of an Instagram icon, positioning it in the top-right corner and altering its look on hover.

In summary, this CSS code is responsible for the visual design of a webpage, encompassing aspects like fonts, colors, backgrounds, and various elements such as cards, forms, buttons, and icons. Additionally, it incorporates animations and hover effects to enhance the user’s interactive experience.

Now we will see JavaScript code

const ImgUpload =({
  onChange,
  src
})=>
  <label htmlFor="photo-upload" className="custom-file-upload fas">
    <div className="img-wrap img-upload" >
      <img for="photo-upload" src={src}/>
    </div>
    <input id="photo-upload" type="file" onChange={onChange}/> 
  </label>


const Name =({
  onChange,
  value
})=>
  <div className="field">
    <label htmlFor="name">
      name:
    </label>
    <input 
      id="name" 
      type="text" 
      onChange={onChange} 
      maxlength="25" 
      value={value} 
      placeholder="Alexa" 
      required/>
  </div>

  
const Status =({
  onChange,
  value
})=>
  <div className="field">
    <label htmlFor="status">
      status:
    </label>
    <input 
      id="status" 
      type="text" 
      onChange={onChange} 
      maxLength="35" 
      value={value} 
      placeholder="It's a nice day!" 
      required/>
  </div>


const Profile =({
  onSubmit,
  src,
  name,
  status,
})=>
  <div className="card">
    <form onSubmit={onSubmit}>
      <h1>Profile Card</h1>
      <label className="custom-file-upload fas">
        <div className="img-wrap" >
          <img for="photo-upload" src={src}/>
        </div>
      </label>
      <div className="name">{name}</div>
      <div className="status">{status}</div>
      <button type="submit" className="edit">Edit Profile </button>
    </form>
  </div>
     
      
const Edit =({
  onSubmit,
  children,
})=>
  <div className="card">
    <form onSubmit={onSubmit}>
      <h1>Profile Card</h1>
        {children}
      <button type="submit" className="save">Save </button>
    </form>
  </div>

class CardProfile extends React.Component {
  state = {
    file: '',
    imagePreviewUrl: 'https://github.com/OlgaKoplik/CodePen/blob/master/profile.jpg?raw=true',
    name:'',
    status:'',
    active: 'edit'
  }

  photoUpload = e =>{
    e.preventDefault();
    const reader = new FileReader();
    const file = e.target.files[0];
    reader.onloadend = () => {
      this.setState({
        file: file,
        imagePreviewUrl: reader.result
      });
    }
    reader.readAsDataURL(file);
  }
  editName = e =>{
    const name = e.target.value;
    this.setState({
      name,
    });
  }
  
  editStatus = e => {
    const status = e.target.value;
    this.setState({
      status,
    });
  }
  
  handleSubmit= e =>{
    e.preventDefault();
    let activeP = this.state.active === 'edit' ? 'profile' : 'edit';
    this.setState({
      active: activeP,
    })
  }
  
  render() {
    const {imagePreviewUrl, 
           name, 
           status, 
           active} = this.state;
    return (
      <div>
        {(active === 'edit')?(
          <Edit onSubmit={this.handleSubmit}>
            <ImgUpload onChange={this.photoUpload} src={imagePreviewUrl}/>
            <Name onChange={this.editName} value={name}/>
            <Status onChange={this.editStatus} value={status}/>
          </Edit>
        ):(
          <Profile 
            onSubmit={this.handleSubmit} 
            src={imagePreviewUrl} 
            name={name} 
            status={status}/>)}
        
      </div>
    )
  }
}

ReactDOM.render(
  <CardProfile/>,
  document.getElementById('root')
)

Certainly! This code appears to define several React functional components and a class component to create a profile card with editing capabilities. Let’s break it down step by step:

  1. ImgUpload Component:
  • This component is responsible for handling image uploads.
  • It takes two props: onChange and src.
  • It renders an input element for file uploads and displays a preview of the selected image.
  • The onChange prop is used to handle changes in the selected image.
  • The src prop is used to display the image preview.
  1. Name and Status Components:
  • These components handle the user’s name and status text.
  • They take onChange and value props.
  • They render input fields for name and status, allowing users to edit them.
  1. Profile Component:
  • This component is responsible for displaying the user’s profile.
  • It takes four props: onSubmit, src, name, and status.
  • It renders a profile card with the user’s image, name, and status.
  • The onSubmit prop is used to handle form submissions.
  1. Edit Component:
  • This component is used for editing the user’s profile.
  • It takes two props: onSubmit and children.
  • It renders an editing form with a “Save” button.
  • The onSubmit prop is used to handle form submissions.
  1. CardProfile Class Component:
  • This class component manages the overall profile card.
  • It has state variables for file, imagePreviewUrl, name, status, and active.
  • The photoUpload method handles image uploads and updates the image preview.
  • The editName and editStatus methods handle changes to the name and status.
  • The handleSubmit method toggles between the “edit” and “profile” modes.
  • The render method renders either the editing form (using Edit) or the user’s profile (using Profile) based on the active state.
  1. ReactDOM Render:
  • The CardProfile a component is rendered into the HTML element with the ID ‘root’.

In summary, this code creates a dynamic user profile card that allows users to edit their name, status, and profile picture. It toggles between edit and profile modes using the state variable active. When in edit mode, it displays an editing form, and in profile mode, it shows the user’s profile. The user can upload an image, edit their name and status, and save their changes.

Profile card with React.js

Here we wrap our tutorial , Incorporating images into your React projects can greatly enhance the visual appeal and functionality of your web applications. Whether you’re building a simple portfolio or a complex web application, the ability to work with images effectively is a valuable skill. Keep exploring and experimenting to make your React applications even more engaging and visually appealing. Happy coding!



Leave a Reply