How to write Validations while uploading file in React - reactjs

I am working with React, and I am trying to upload a file and that file type should be only png.
When I upload png file it is working fine. but I need to stop uploading other type files. for example if I need to upload png file means, it's needs to work properly. by mistake if I upload audio file means the file should not be uploaded. Please tell me how to write validations like this.
This is my code
This is App.js
import React, { useState } from "react";
import 'antd/dist/antd.css';
import './index.css';
import { Row, Col, Button, Modal, Upload, message } from 'antd';
import { VideoCameraOutlined, AudioOutlined } from '#ant-design/icons';
import "./App.css";
const App = () => {
const props = {
beforeUpload: file => {
const audioValidation = file.type === "image/png"
if (!audioValidation) {
message.error('You can only upload PNG file!');
}
}
}
const [visible, setVisible] = useState(false)
const showPopUp = () => {
setVisible(true)
}
return (
<div>
<Row>
<Col span={24}>
<Button onClick={() => showPopUp()} type="primary">Show PopUp</Button>
<Modal
visible={visible}
>
<Upload {...props}>
<div style={{ display: "flex" }}>
<div>
<VideoCameraOutlined style={{ fontSize: "25px", backgroundColor: "red", padding: "10px", borderRadius: "50%" }} />
<h6>Upload Video</h6>
</div>
<div style={{ marginLeft: "5px" }}>
<AudioOutlined style={{ fontSize: "25px", backgroundColor: "red", padding: "10px", borderRadius: "50%" }} />
<h6>Upload Png</h6>
</div>
</div>
</Upload>
</Modal>
</Col>
</Row>
</div>
)
}
export default App
If you have any questions please let me know, thank you.

In the Antd documentation they tell you that you can use the 'accept' property to select the formats to be chosen by the end user, that way you do not have to verify anything, since it will only allow you to select that type of files. Basically as a normal input.
Antd Documentation Here

From the MDN doc page on <input>:
The accept attribute value is a string that defines the file types the file input should accept. This string is a comma-separated list of unique file type specifiers. Because a given file type may be identified in more than one manner, it's useful to provide a thorough set of type specifiers when you need files of a given format.
We can specify that an input should only accept .png files with the following:
<input type="file" accept=".png">
However, it appears that you're using Ant Design, and it doesn't look like the <Upload> component actually has a built-in way to provide accepted file types to the <input> element. Maybe this is something you can work around with the above information.

Ok, I read the code on github and this is what you should do.
beforeUpload: file => {
const audioValidation = file.type === "image/png"
return new Promise((resolve, reject) => {
if (!audioValidation) {
reject(null) // the file is not ok then abort
message.error('You can only upload PNG file!');
}else resolve(file) // the file is ok, so you should proceed.
}
}

Related

creating PDF black background instead of image via jsPDF in React js

Hi I am creating pdf with image background via jsPDF library. File creating successfully but making background black instead of image my code is this.
const exportBrocharPDF = () => {
let element = (
<div style={{ textAlign: "left", width:"600px"}}>
<div style={{ backgroundImage: `url("https://mentorlogix.com/pricebuilder/pdfimages/4.png")`}}>
<p style={{fontSize: "10px", color:"#000"}}>
Your investment in the maintenance package is just , billed directly to your credit card.
</p>
</div>
</div>
)
const doc = new jsPDF("p", "pt", "a4");
doc.html(ReactDOMServer.renderToString(element), {
callback: function (doc) {
doc.save('Brochar.pdf');
}
});
};
Result is like this
I am trying a lot but not success please anyone can help to resolve my issue

Trying to implement local storage in React. It is not tracking the input value that I send

I am trying to implement a local storage in REACT in order to save in a database the data(numbers) that I type in the input. The code works when I check it in the console.log but it does not work as I wish. Everytime I add a value it deletes the previous one. So I can just read the last input that I put. It does not shows me all the inputs that I put before. I would like to mention that this component is rendered dinamycally so in the parent component I get four different buttons where I can type the number that I want to. Thanks in advance
import React, { useState, useEffect } from 'react';
function Stake() {
const [stakes, setStakes] = useState([]);
const addStake = (e) => {
e.preventDefault();
const newStake = {
input: e.target.stake.value,
};
setStakes([...stakes, newStake]);
};
useEffect(() => {
const json = JSON.stringify(stakes);
localStorage.setItem("stakes", json);
}, [stakes]);
console.log(stakes)
return (
<div>
<form onSubmit={addStake}>
<input style={{ marginLeft: "40px", width: "50px" }} type="text" name="stake" required />
{/* <button style={{ marginLeft: "40px" }} type="submit">OK</button> */}
</form>
</div>
);
}
export default Stake;
Right now your component always starts with an empty array: useState([]).
When the component renders for the first time, you need to retrieve existing values from locaStorage and set it as the local state of component:
useEffect(() => {
const stakes= JSON.parse(localStorage.getItem("stakes")) || [];
setStakes(stakes);
}, []);

Trying to iterate an array of URL's in React?

I am trying to create an image gallery using Heroku's new add:on 'simple-file-upload'. I've managed to get everything saved to the database and I can display 1 image at a time, but am having trouble creating the gallery now. I've set everything up how I think it should be, but when I console.log(files) I am not receiving the URL, but rather just the number 1 from the count. Any ideas what I'm doing wrong here? Here is my code below:
import React from "react";
import SimpleFileUpload, { SimpleFileUploadProvider } from "../components/SimpleFileUpload"
import { useState } from 'react'
import "./styles.css"
const API_KEY = ''
let count = 0;
export default function About() {
const [files, setFiles] = useState([]);
console.log(files)
//var Gallery = [];
//Gallery.push(files);
//console.log(files)
return (
<div className="App">
<h1>upload an image</h1>
<SimpleFileUpload apiKey={API_KEY} onSuccess={() => setFiles([...files, `${++count}`])} />
{!!files &&
files.map(a => {
return (
<div
key={a}
style={{
display: "flex",
justifyContent: "space-between",
marginTop: 5
}}
>
<div>{a}</div>
{/*
button to remove entries from the array, this should also make an API call to remove them from your server (unless the files are required for something like an audit).
*/}
<button onClick={() => setFiles(files.filter(f => f !== a))}>
Remove
</button>
</div>
);
})}
</div>
);
}
It looks like your onSuccess handler isn't accepting files. the ...files in () => setFiles([...files, ${++count}]) is the files from const [files, setFiles] = useState([]);, ie, [], leaving you with ${++count}, ie, 1.
changing it to files => setFiles([...files ${++count}]) should fix it---though i don't know what onSuccess does, so i can't say for sure.

http://localhost:3000/[object%20Object] not found 404

In my react app, this is an array of filenames I get from server side
const photos = ["01-1913.JPG", "01-1913.1.jpg", "01-1913.2.jpg"]
and here is how I use it with JSX
{
photos.map(entry => {
return (
<div key={entry}>
<PhotoItem key={entry} url={`${process.env.REACT_APP_NODE_SERVER}/${entry}`} />
</div>
)
})
}
const PhotoItem = (url) => {
return (
<img
src={url}
onError={this.addDefaultSrc}
alt="photoItem"
style={{
width: "500px",
height: "600px",
border: "1px solid #123C69",
}}
></img>
);
};
```
I can not figure out why I am not getting the photo (only the dummy photo from the onError event I've used) and if it has anything to do with the Object%object error. Any help would be appreciated.
As mentioned in the comments, the PhotoItem component should look like this:
// Note that here props are named "props" instead of "url"
const PhotoItem = (props) => {
return (
<img
src={props.url}
onError={this.addDefaultSrc}
alt="photoItem"
style={{
width: "500px",
height: "600px",
border: "1px solid #123C69",
}}
></img>
);
};
Note that the first argument that a react component receives is props. So even if you name it url, the value that you are looking for url lives in url.url.
I also recommend to deconstruct your props like this:
const PhotoItem = ({url}) => {
return (
<img
src={url}
...
></img>
);
};
I faced this error on the developer console on a Next.js project right after upgrading Next from v10 to v12.
Turns out using an image as <img src={require()}/> is not working anymore, and throws this error.
Instead to fix the issue, you need to use Next's (almost) drop in replacement of Image component as;
import Image from 'next/image'
...
<Image src={require()}/>
This will fix the issue, if your Next project is throwing this error.

Resize google map frame in react js

Currently using google-maps-react component in a contact form for a sales page. This code has successfully imported the map and it is viewable in the dimensions 450x350. My issue is, is that despite the image being 450x350 the frame or i guess div that the map api sits in still thinks the map is still default size so it pushes my entire site out with white space that is removed when i remove the Map API. No amount of adding styles as dimensions to anything around the map has fixed this.
What do i pass into the map in order to effect the size of the frame and not just the image itself?
import React, { Fragment } from "react";
import ContactForm from "../contactus/ContactForm";
import { Map, Marker, GoogleApiWrapper } from "google-maps-react";
const ContactUs = props => {
const style = {
maxWidth: "450px",
height: "350px",
overflowX: "hidden",
overflowY: "hidden"
};
return (
<Fragment>
<h2 className='lead text-primary text-center'>Get in touch</h2>
<div className='grid-2'>
<div>
<h4>Priority Consulting</h4>
<ul>
<li>
1234 Sherman Way <br />
Sherman Oaks, CA 90210
</li>
<li>info#priorityconsulting.com</li>
<li>1-800-324-3423</li>
</ul>
<Map google={props.google} style={style} />
</div>
<div>
{" "}
<ContactForm />
</div>
</div>
</Fragment>
);
};
export default GoogleApiWrapper({
apiKey: "MYKEY"
})(ContactUs);
I went back into my code and found an updated version, that made it to a final version of the site. Unfortunately the site is no longer live so cant verify if this is the best answer but, like I said its in my code, so it probably solves.
const style = {
maxWidth: "450px",
height: "350px",
overflowX: "hidden",
overflowY: "hidden"
};
const containerStyle = {
maxWidth: "450px",
height: "350px"
};
<Map google={props.google} style={style} containerStyle={containerStyle} />

Resources