Hey All 👋👋👋
It's been a while since I wrote an article. Due to work and life, I wasn't able to keep up with my blog, but I'm back now and I'll try to be more consistent. Moving on, I am about to discuss something that was given to me as part of my interview task. Which was to create a preview of the picture before it is uploaded.
Here, I have used a React application. After clearing the app.js file, the code now looks like this:
export default function App() {
return (
<div className="App">
</div>
);
}
Then I added a header and a div which will contain input and an image:
export default function App() {
return (
<div className="App">
<h1>Image Upload Preview</h1>
<div className="imageContainer">
</div>
</div>
);
}
After that, I added the styles:
import "./styles.css";
export default function App() {
return (
<div className="App">
<h1>Image Upload Preview</h1>
<div className="imageContainer">
</div>
</div>
);
}
.App {
font-family: sans-serif;
text-align: center;
}
.imageContainer {
display: flex;
flex-direction: column;
align-items: center;
}
Then I added an input for uploading the picture and used a state to store it:
import "./styles.css";
import { useState } from "react";
export default function App() {
const [image, setImage] = useState(null);
const handleImageUpload = (e) => {
setImage(URL.createObjectURL(e.target.files[0]));
};
return (
<div className="App">
<h1>Image Upload Preview</h1>
<div className="imageContainer">
<input type="file" accept="image/*" onChange={handleImageUpload} />
</div>
</div>
);
}
Note: The URL.createObjectURL() static method creates a string containing a URL representing the object given in the parameter. Read more ->
Now the page would look something like this:
Lastly, I displayed the image if it existed and added styles:
import { useState } from "react";
import "./styles.css";
export default function App() {
const [image, setImage] = useState(null);
const handleImageUpload = (e) => {
setImage(URL.createObjectURL(e.target.files[0]));
};
return (
<div className="App">
<h1>Image Upload Preview</h1>
<div className="imageContainer">
<input type="file" accept="image/*" onChange={handleImageUpload} />
{image ? <img src={image} className="image" alt="preview" /> : null}
</div>
</div>
);
}
.App {
font-family: sans-serif;
text-align: center;
}
.imageContainer {
display: flex;
flex-direction: column;
align-items: center;
}
.image {
height: 200px;
width: 200px;
margin-top: 20px;
border: 1px solid black;
border-radius: 5px;
}
The final result after uploading a picture:
Thanks for reading. Have a nice day. 🙂
Let's connect - 👋👋👋
Top comments (0)