Browser not previewing image that was previously uploaded - reactjs

I have a component in React that is responsible for image preview. I also have an option for removing the image. I have noticed that if I have uploaded an image, and then removed it, that I can't preview it if I want to upload it again. Why is that happening?
This is my component:
class MediaPlaceholder extends Component {
constructor(props) {
super(props)
this.state = {
fileUrl: null
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event) {
this.setState({
fileUrl: URL.createObjectURL(event.target.files[0])
})
}
removeImage() {
this.setState((prevState) => {
URL.revokeObjectURL(prevState.fileUrl);
return {fileUrl: null};
});
}
render() {
const {classes} = this.props;
const {fileUrl} = this.state;
return (
<Paper className={classes.media}>
{fileUrl &&
<div className={classes.imageWrapper}>
<IconButton aria-label="Clear" className={classes.iconButton} onClick={() => this.removeImage()}>
<ClearIcon/>
</IconButton>
<img src={fileUrl} className={classes.image}/>
</div>
}
<input
accept="image/*"
className={classes.input}
id="upload-file"
type="file"
onChange={(event) => this.handleChange(event)}
/>
<label htmlFor="upload-file">
<Button component="span">
Add media...
</Button>
</label>
</Paper>
);
}
}

Related

how do I hide/display the submit button in React JS

I am completely new to React JS, I have no Idea how to do in ReactJS.
I have to hide the Submit button initially, when keyin to dates fields then Submit button should be display.
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = { startdate: '', enddate: '' };
}
mySubmitHandler = (event) => {
event.preventDefault();
alert("You are submitting " + this.state.startdate +"and"+ this.state.enddate);
}
myChangeHandler = (event) => {
this.setState({startdate: event.target.value});
}
myEndDate = (event) => {
this.setState({enddate: event.target.value});
}
render() {
return (
<form onSubmit={this.mySubmitHandler}>
<img src="C:\\Users\\A9002255\\Desktop\is.jpg"></img>
<h2>Please select the Date range of .CSV </h2>
<input
type='date'
onChange={this.myChangeHandler}
/>
<span> </span>
<input
type="date"
onChange={this.myEndDate}
/>
<div>
<input
type='submit' value="Download" class="bi bi-cloud-arrow-down" style={{ width: '10%', height: 30}}
/>
</div>
</form>
);
}
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
export default MyForm;
You can add check on base of start and end dates of your state.
Try following code
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = { startdate: '', enddate: '' };
}
mySubmitHandler = (event) => {
event.preventDefault();
alert("You are submitting " + this.state.startdate +"and"+ this.state.enddate);
}
myChangeHandler = (event) => {
this.setState({startdate: event.target.value});
}
myEndDate = (event) => {
this.setState({enddate: event.target.value});
}
render() {
return (
<form onSubmit={this.mySubmitHandler}>
<img src="C:\\Users\\A9002255\\Desktop\is.jpg"></img>
<h2>Please select the Date range of .CSV </h2>
<input
type='date'
onChange={this.myChangeHandler}
/>
<span> </span>
<input
type="date"
onChange={this.myEndDate}
/>
<div>
{this.state.startdate && this.state.enddate && <input
type='submit' value="Download" class="bi bi-cloud-arrow-down" style={{ width: '10%', height: 30}}
/>}
</div>
</form>
);
}
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
export default MyForm;

I need to pass a URL from a class component to another

here is my QR component :
import React, { Component } from "react";
class QR extends React.Component {
constructor(props) {
super(props);
}
render() {
const { catImageUrl } = this.props;
const qrUrl = `https://qrtag.net/api/qr_12.svg?url=${catImageUrl}`;
if (!catImageUrl) return <p>Oops, something went wrong!</p>;
return <img className="QR" src={qrUrl} alt="qrtag" />;
}
}
export default QR;
I need to pass the const qrURL to the next component Form.js to use it in ajax call to get its data and pass it to the next api request to send it to an email
class Form extends React.Component{
constructor(props) {
super(props);
this.state = {
name: '',
email: '',
message: '',
}
}
const{qrUrl}=this.props;
FetchQRURL = () => {
fetch(`${qrUrl}`)
.then((response) => response.json())
.then((data) => {
this.setState({
message: data,
});
})
.catch((error) => console.log(error));
};
handleSubmit(e){
e.preventDefault();
axios({
method: "POST",
url:"http://localhost:3002/send",
data: this.state
}).then((response)=>{
if (response.data.status === 'success'){
alert("Message Sent.");
this.resetForm()
}else if(response.data.status === 'fail'){
alert("Message failed to send.")
}
})
}
resetForm(){
this.setState({name: '', email: '', message: ''})
}
render() {
return(
<div className="App">
<form id="contact-form" onSubmit={this.handleSubmit.bind(this)} method="POST">
<div className="form-group">
<label htmlFor="name">Name</label>
<input type="text" className="form-control" id="name" value={this.state.name} onChange={this.onNameChange.bind(this)} />
</div>
<div className="form-group">
<label htmlFor="exampleInputEmail1">Email address</label>
<input type="email" className="form-control" id="email" aria-describedby="emailHelp" value={this.state.email} onChange={this.onEmailChange.bind(this)} />
</div>
<div className="form-group">
<label htmlFor="message">Message</label>
<textarea className="form-control" rows="5" id="message" value={this.state.message} onChange={this.onMessageChange.bind(this)} />
</div>
<button type="submit" className="btn btn-primary" onClick="">Submit</button>
</form>
</div>
);
}
onNameChange(event) {
this.setState({name: event.target.value})
}
onEmailChange(event) {
this.setState({email: event.target.value})
}
onMessageChange(event) {
this.setState({message: event.target.value})
}
}
export default Form;
you can see I tried to pass it as props but it doesn't work
here I tried to pass it as props(in my app.js)
import React, { Component } from "react";
import RandomCat from "./RandomCat.js";
import QR from "./QR.js";
import Form from "./form.js";
class BooksApp extends Component {
state = {
showCatImage: false,
showQrCode: false,
catImageUrl: "",
};
handleFetchRandomImage = () => {
fetch("https://aws.random.cat/meow")
.then((response) => response.json())
.then((data) => {
this.setState({
catImageUrl: data.file,
showCatImage: true,
});
})
.catch((error) => console.log(error));
};
handleShowQrCode = () => {
this.setState({ showQrCode: true });
};
render() {
const { showCatImage, showQrCode, catImageUrl,qrUrl } = this.state;
return (
<div className="app">
<div className="first">
{/* The time below shows cat image if showCatImage === true and returns nothing if false */}
{showCatImage && <RandomCat catImageUrl={catImageUrl} />}
<button className="catButton" onClick={this.handleFetchRandomImage}>
Generate Cat
</button>
</div>
<div className="second">
{showQrCode && <QR catImageUrl={catImageUrl} qrUrl={qrUrl}/>}
<button className="QRButton" onClick={this.handleShowQrCode}>
Geanerate QR
</button>
</div>
<div>
<Form qrUrl={qrUrl}/>
</div>
</div>
);
}
}
export default BooksApp;
any idea how can I pass it to the Form.js?
You have to pull the constant qrUrl to the parent component which is BooksApp in your case.
Set it to the state and pass it down as props.
state = {
showCatImage: false,
showQrCode: false,
catImageUrl: "",
qrUrl: ""
};
handleFetchRandomImage = () => {
fetch("https://aws.random.cat/meow")
.then((response) => response.json())
.then((data) => {
this.setState({
catImageUrl: data.file,
showCatImage: true,
qrUrl: `https://qrtag.net/api/qr_12.svg?url=${data.file}` // Set it here
});
})
.catch((error) => console.log(error));
};
handleShowQrCode = () => {
this.setState({ showQrCode: true });
};
render() {
const { showCatImage, showQrCode, catImageUrl, qrUrl } = this.state;
return (
<div className="app">
<div className="first">
{/* The time below shows cat image if showCatImage === true and returns nothing if false */}
{showCatImage && <RandomCat catImageUrl={catImageUrl} />}
<button className="catButton" onClick={this.handleFetchRandomImage}>
Generate Cat
</button>
</div>
<div className="second">
{showQrCode && <QR catImageUrl={catImageUrl} qrUrl={qrUrl}/>}
<button className="QRButton" onClick={this.handleShowQrCode}>
Geanerate QR
</button>
</div>
<div>
<Form qrUrl={qrUrl}/>
</div>
</div>
);
}
}
export default BooksApp;
The just use it with this.props.qrUrl in your other components.

React mui button input file not opening local machin file directory

I am trying to implement a button as an input field of file type, I have tried to wrap the input field with the button, and hide it. But, this is not working since nothing happens when I click on the button. I don't get the dialog to choose the files from the local machine. This is my component:
class MediaPlaceholder extends Component {
constructor(props){
super(props)
this.state = {
file: null
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event) {
this.setState({
file: URL.createObjectURL(event.target.files[0])
})
}
render() {
const {classes} = this.props;
return (
<Paper className={classes.media}>
<div>
<label htmlFor="upload-file">
<Button onClick={event => this.handleChange(event)}>
Add media...
<input
accept="image/*"
className={classes.input}
id="upload-file"
type="file"
/>
</Button>
</label>
</div>
</Paper>
);
}
}
I saw in few places that this is the suggested solution, so I am wondering why is it not working?
From the Material-UI docs/example https://material-ui.com/components/buttons/#contained-buttons :
<input
accept="image/*"
className={classes.input}
id="contained-button-file"
multiple
type="file"
/>
<label htmlFor="contained-button-file">
<Button variant="contained" component="span" className={classes.button}>
Upload
</Button>
</label>
So you could try :
class MediaPlaceholder extends Component {
constructor(props){
super(props)
this.state = {
file: null
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event) {
this.setState({
file: URL.createObjectURL(event.target.files[0])
})
}
render() {
const {classes} = this.props;
return (
<Paper className={classes.media}>
<div>
<input
accept="image/*"
className={classes.input}
id="upload-file"
type="file"
/>
<label htmlFor="upload-file">
<Button onClick={this.handleChange.bind(this)}>
Add media...
</Button>
</label>
</div>
</Paper>
);
}
}

Event / callback for when a user logs in with Meteor + React?

Im using Meteor and React. I need to redirect a user when they log in. Is there an event or callback for this?
import React from 'react';
import { Link, Redirect } from 'react-router-dom';
import './LogInPage.less';
class LogIn extends React.Component {
constructor(props) {
super(props);
this.state = {
error: false,
loggedIn: Meteor.userId() ? true : false,
};
this.login = this.login.bind(this);
}
login = e => {
e.preventDefault();
Meteor.loginWithPassword(this.email.value, this.password.value, err => {
if (err) {
this.setState({ error: err.reason });
}
});
// if (Meteor.userId()) this.setState({ loggedIn: true });
};
render() {
// if (Meteor.userId()) return <Redirect to="/" />;
return (
<div className="LogIn">
<form onSubmit={this.login}>
<label>Email</label>
<input type="email" ref={input => (this.email =
<label>Password</label>
<input type="password" ref={input => (this.password = input)} />
<button className="btn" type="submit">
Log in
</button>
{this.state.error && (
<p className="form-std__msg form-std__msg--err">
{this.state.error}
</p>
)}
</form>
</div>
);
}
}
export default LogInPage;
If no error then you can check using Meteor.user()
import React from 'react';
import { Link, Redirect } from 'react-router-dom';
import './LogInPage.less';
class LogIn extends React.Component {
constructor(props) {
super(props);
this.state = {
error: false,
loggedIn: Meteor.userId() ? true : false,
};
this.login = this.login.bind(this);
}
login = e => {
e.preventDefault();
Meteor.loginWithPassword(this.email.value, this.password.value, err => {
if (err) {
this.setState({ error: err.reason });
} else {
this.setState({ loggedIn: Meteor.user() ? true : false })
}
});
// if (Meteor.userId()) this.setState({ loggedIn: true });
};
render() {
if (this.state.loggedIn) return <Redirect to="/" />;
return (
<div className="LogIn">
<form onSubmit={this.login}>
<label>Email</label>
<input type="email" ref={input => (this.email = input)} />
<label>Password</label>
<input type="password" ref={input => (this.password = input)} />
<button className="btn" type="submit">
Log in
</button>
{this.state.error && (
<p className="form-std__msg form-std__msg--err">
{this.state.error}
</p>
)}
</form>
</div>
);
}
}
export default LogInPage;

Disable / hide button depending on checkbox

Is there a way to disable or hide a if the is checked ?
I would like to make CreateQuotation & TakeNotes buttons to hide or disable when the checkbox is not checked
Heres how my code looks like
const renderCheckbox = ({ input, label }) =>
<FormControlLabel
control={
<Checkbox
{...input}
checked={input.value ? true : false}
onCheck={input.onChange}
/>
}
label={label}
/>
const CreateReport = (props) => {
const { handleSubmit, pristine, submitting } = props;
return (
<div className="create-report-form-container mobile-padding">
<form onSubmit={handleSubmit}>
<div>
<Field name="quotation-checkbox" component={renderCheckbox} label="Quotation to do" />
</div>
<div>
<Button raised color="accent" label="CreateQuotation">
Create a Quotation
</Button>
<Button raised color="accent" label="TakeNotes">
Take some notes
</Button>
</div>
<Button raised color="accent" type="submit" label="send" disabled={pristine || submitting}>
Send
</Button>
</form>
</div>
);
};
export default reduxForm({
form: 'CreateReport',
enableReinitialize: true,
})(CreateReport);
I would add a constant variable like isActive which is toggling the checkbox state and to show and hide the Button you can do this in the return area:
{ isActive ? <Button>create Quotation & Take notes </Button> : null }
You can get the isActive state with calling a function in the state change:
<input
type="checkbox"
onChange={(event) => this.handleCheck(event)}
checked={true}
/>
constructor(props) {
super(props);
this.state = {
isActive: {}
};
this.handleCheck = this.handleCheck.bind(this);
}
handleCheck(event){
isActive = event.target.checked;
this.setState({ isActive: isActive });
}
class Rq extends Component {
constructor(){
super();
this.state = {
option: '',
isDisabled: true,
checked: true
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(){
this.setState({checked: !this.state.checked});
if (this.state.checked)
{
this.setState({isDisabled: false})
}
else
this.setState({isDisabled: true});
}
handleSubmit(e){
e.preventDefault();
if (this.state.isDisabled===false) {
alert('Form submitted')
} else
{
alert('form has not submitted');
}
}

Resources