How to write these plugin initialized in functional component? - reactjs

I got an example like this
Before ever thing I need to import the payment from the plugin
import Payment from 'react-gg-payment';
This is the code from the website. example is given in classco
class App extends Component<Props> {
constructor(props) {
super(props);
this.state = {
isLoading : false,
payment_status : 'initiated'
};
var appServiceConfigData = {
"environment" : "test",
"base_url": "https://checkoutshopper-test.com/checkoutshopper/demoserver/",
"additional_http_headers" : {
"x-demo-server-api-key": DEMO_SERVER_API_KEY
}
};
Payment.initialize(appServiceConfigData);
Payment.onSuccess((payload) => {
this.setState({payment_status: 'success'});
console.log(payload);
});
Payment.onError((code, error) => {
console.log("Error : ",error);
this.setState({payment_status: 'failure'});
});
}
This is the example given by the library.
What I want is I wanna convert these codes into function component.
I don't know whether my code is true or false. This is my progress so far
const FuncApp = ({navigation}) => {
const [loading, setLoading] = useState(false);
const [paymentStatus, setPaymentStatus] = useState('initiated');
useEffect(() => {
var appServiceConfigData = {
"environment" : "test",
"base_url": "https://checkoutshopper-test.com/checkoutshopper/demoserver/",
"additional_http_headers" : {
"x-demo-server-api-key": DEMO_SERVER_API_KEY
}
};
Payment.initialize(appServiceConfigData);
},[])
//IDK WHERE TO PUT BELOW CODES
Payment.onSuccess((payload) => {
setPaymentStatus('success');
console.log(payload);
});
Payment.onError((code, error) => {
console.log("Error : ",error);
setPaymentStatus('failure');
});
in the return statement.
I got a button with onPress
const onClickPayment = () => {
Payment.startPayment()
}
<Button
label={'Pay'}
title="Pay"
color="#841584"
onPress={() => {
onClickPayment();
}}
/>

Related

how to create refs for content that gets created later

I have a component that fetches data from an api upon user input. This data then gets rendered onto the screen as <li/> tags. I want those <li/> tags to have a ref.
I tried creating an object of refs that I create after the data is fetched:
this.singleRefs = data.reduce((acc, value) => {
acc[value.id] = React.createRef();
return acc;
}, {});
and then later assign these refs to the <li/> tag: <li ref={this.singleRefs[element.id]}>
but when I print them out I always have {current:null} Here is a demo
what am I doing wrong?
With dynamic ref data, I'd propose that you should use callback refs.
import React from "react";
import "./styles.css";
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
this.singleRefs = {};
}
componentDidMount() {
const data = [
{ value: "val1", id: 1 },
{ value: "val2", id: 2 },
{ value: "val3", id: 3 }
];
this.myFunc(data);
//you don't need this anymore
// this.singleRefs = data.reduce((acc, value) => {
// acc[value.id] = React.createRef();
// return acc;
// }, {});
}
myFunc = async (data) => {
await sleep(3000);
this.setState({ data });
};
renderContent() {
return this.state.data.map(
function (element, index) {
return (
<li key={index} ref={(node) => (this.singleRefs[element.id] = node)}>
{element.value}
</li>
);
}.bind(this)
);
}
render() {
console.log(this.singleRefs);
return <ul>{this.renderContent()}</ul>;
}
}
Sandbox

React Native : Dynamically Created TextBox value is not getting updated

I'm little new to React Native. I have a scenario where I need to create the TextInput dynamically and bind values it from an array. Once the array updates, the value of the TextInput is not updating. Below is my code.
constructor(props) {
super(props);
this.state = {
textInputValues: [],
textInput: [],
samplearray://gets an array from the JSON
}
componentDidMount() {
this.setTextInputValue();
this.prepareTextBox();
}
setTextInputValue() {
let textInputValues = this.state.textInputValues;
this.state.samplearray.map(() => {
textInputValues.push("") //default value
this.setState({ textInputValues })
})
}
prepareTextBox() {
let textInput = this.state.textInput;
this.state.samplearray.map((value, index) => {
textInput.push(<TextInput style={styles.textBox} value={this.state.textInputValues[index]} key={index} />);
})
this.setState({ textInput })}
Code to render the TextBox in the render method.
{ this.state.textInput.map((value, index) => {
return value
})}
I have button on which this.state.textInputValues array value gets changed. But change of that is not being reflected in the TextInput. Stuck with this since 2 days. Any help is appreciated, thanks in advance.
This is how your code block should look (do read the comments for explanation):
componentDidMount() {
this.setTextInputValue();
// call the below function from `setTextInputValue` as you have dependency on that
// this.prepareTextBox();
}
setTextInputValue() {
let textInputValues = [...this.state.textInputValues];
this.state.samplearray.map((value) => {
textInputValues = [ ...textInputValues , value] //default value
// this is how you should call `prepareTextBox`
// in setState callback as it will confirm that state is updated
this.setState({ textInputValues },() => {
this.prepareTextBox();
})
})
}
prepareTextBox() {
let textInput = [...this.state.textInput];
this.state.samplearray.map((value, index) => {
textInput.push(<input value={this.state.textInputValues[index]} key={index} />);
})
this.setState({ textInput })
}
You can run the below snippet and check, hope that will clear your doubts :
const { useState , useEffect } = React;
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
textInputValues: [],
textInput: [],
samplearray:["Vivek","Darshita"]//gets an array from the JSON
}
}
componentDidMount() {
this.setTextInputValue();
}
setTextInputValue() {
let textInputValues = [...this.state.textInputValues];
this.state.samplearray.map((value) => {
textInputValues = [ ...textInputValues , value] //default value
this.setState({ textInputValues },() => {
this.prepareTextBox();
})
})
}
prepareTextBox() {
let textInput = [...this.state.textInput];
this.state.samplearray.map((value, index) => {
textInput.push(<input value={this.state.textInputValues[index]} key={index} />);
})
this.setState({ textInput })
}
changeValues = () => {
this.setState({
textInput : [],
textInputValues : ["New - Vivek" , "New - Darshita"]
},() => {
this.prepareTextBox();
});
}
render() {
return (
<div>
{ this.state.textInput }
<button onClick={this.changeValues}>Change Value</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>

default language based on user profile language selected

I am working on the language translation using i18n. I have a ToggleSwitch to change the language of the content which is working fine. But I want to make the default language according to user profile language selected.
This is the code I am using.
Any help?
constructor(props) {
super(props)
this._retrieveData()
this.state = {
isOnBlueToggleSwitch: false
}
}
onToggle = (isOn) => {
I18n.locale = isOn ? "th" : "en"
}
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('user');
if (value !== null) {
localLanguage = JSON.parse(value);
I18n.locale = localLanguage.lang;
}
} catch (error) {
console.log(error)
}
}
render() {
return (
<View style={styles.container}>
<ToggleSwitch
onColor="#52a557"
size='small'
isOn={this.state.isOnBlueToggleSwitch}
onToggle={isOnBlueToggleSwitch => {
this.setState({ isOnBlueToggleSwitch });
this.onToggle(isOnBlueToggleSwitch);
}}
/>
</View>
)
}
i18n.js
'use strict';
import I18n from 'react-native-i18n';
I18n.fallbacks = true;
// List of language
I18n.translations = {
'en': require('./en'), //for English
'th': require('./th'),
};
export default I18n;

Recaptcha Missing required parameters: sitekey

I'm integrating recaptcha to my react app and I'm having this error: "Missing required parameters: sitekey" when I use the render method of grecaptch even though I have properly included the sitekey in to the parameters.
Here is my code for reference:
class ReCaptcha extends React.Component {
componentDidMount() {
this.callbackName = 'g-lf-callback';
window[this.callbackName] = this.props.callback;
if(window.grecaptcha) {
this.renderRecaptcha();
} else {
this.loadRecaptchaScript();
}
}
componentWillUnmount() {
delete window['rconload'];
delete window[this.callbackName];
}
loadRecaptchaScript() {
window['rconload'] = () => {
this.renderRecaptcha();
};
let url = 'https://www.google.com/recaptcha/api.js?onload=rconload&render=explicit';
loadScript(url, '', 'recaptcha', true, true)
.then( () => {})
.catch( () => {});
}
renderRecaptcha = () => {
if(this.container) {
let parameters = {
sitekey: process.env.MY_SITEKEY,
size: 'invisible',
badge: null,
callback: 'g-lf-callback'
};
const recaptchaId = window.grecaptcha.render(this.container, parameters);
this.execute = () => window.grecaptcha.execute(recaptchaId);
this.reset = () => window.grecaptcha.reset(recaptchaId);
this.getResponse = () => window.grecaptcha.getResponse(recaptchaId);
}
}
onClick = () => {
this.execute();
}
render() {
let { callback, label, className, ...btnProps } = this.props;
return (
<Button
{ ...btnProps }
className={ className }
onClick={ this.onClick }
ref = { ref => this.container = ref }
>
{ label }
</Button>
)
}
}
I have also set the render parameter of recaptcha url to explicit
https://www.google.com/recaptcha/api.js?onload=rconload&render=explicit
Onload callback:
window['rconload'] = () => {
this.renderRecaptcha();
};

Lot of repetition in React component

I have a rather large React component that manages the display of a detail for a job on my site.
There are a few things that I would like to do smarter
The component has a few options for opening Dialogs. For each dialog I have a separate Open and Close function. For example handleImageGridShow and handleImageGridClose. Is there any way to be more concise around this?
I have many presentational components (e.g. ViewJobDetails) that shows details about the job. My issue is that I have to pass them down into each Component as a prop and I'm passing the same props over and over again
As I'm loading my data from firebase I often have to do similar checks to see if the data exists before I render the component (e.g.this.state.selectedImageGrid && <ImageGridDialog />). Is there any more clever way of going about this?
import React, { Component } from 'react';
import { withStyles } from 'material-ui/styles';
import ViewJobAttachment from "../../components/jobs/viewJobAttachment";
import ViewJobDetails from "../../components/jobs/viewJob/viewJobDetails";
import ViewJobActions from "../../components/jobs/viewJob/viewJobActions";
import ViewCompanyDetails from "../../components/jobs/viewJob/viewCompanyDetails";
import ViewClientsDetails from "../../components/jobs/viewJob/viewClientsDetails";
import ViewProductsDetails from "../../components/jobs/viewJob/viewProductsDetails";
import ViewAttachmentDetails from "../../components/jobs/viewJob/viewAttachmentDetails";
import ViewEventLogDetails from "../../components/jobs/viewJob/viewEventLogDetails";
import ViewSummaryDetails from "../../components/jobs/viewJob/viewSummary";
import {FirebaseList} from "../../utils/firebase/firebaseList";
import SimpleSnackbar from "../../components/shared/snackbar";
import {calculateTotalPerProduct} from "../../utils/jobsService";
import BasicDialog from "../../components/shared/dialog";
import ImageGrid from "../../components/shared/imageGrid";
import Spinner from "../../components/shared/spinner";
import ViewPinnedImageDialog from "../../components/jobs/viewEntry/viewPinnedImage";
import {
Redirect
} from 'react-router-dom';
const styles = theme => ({
wrapper: {
marginBottom: theme.spacing.unit*2
},
rightElement: {
float: 'right'
}
});
const ImageGridDialog = (props) => {
return (
<BasicDialog open={!!props.selectedImageGrid}
handleRequestClose={props.handleRequestClose}
fullScreen={props.fullScreen}
title={props.title}
>
<ImageGrid selectedUploads={props.selectedImageGrid}
handleClickOpen={props.handleClickOpen}/>
</BasicDialog>
)
};
class ViewJob extends Component {
constructor() {
super();
this.state = {
currentJob: null,
entries: [],
promiseResolved: false,
attachmentDialogOpen: false,
openAttachment: null,
selectedImageGrid: false,
selectedPinnedImage: false,
showSnackbar: false,
snackbarMsg: '',
markedImageLoaded: false,
loading: true,
redirect: false
};
this.firebase = new FirebaseList('jobs');
this.handleJobStatusChange = this.handleJobStatusChange.bind(this);
this.handleImageGridShow = this.handleImageGridShow.bind(this);
this.handleImageGridClose = this.handleImageGridClose.bind(this);
this.handlePinnedImageClose = this.handlePinnedImageClose.bind(this);
this.handlePinnedImageShow = this.handlePinnedImageShow.bind(this);
this.handleMarkedImageLoaded = this.handleMarkedImageLoaded.bind(this);
this.handleRemove = this.handleRemove.bind(this);
this.pushLiveToClient = this.pushLiveToClient.bind(this);
}
componentDidMount() {
this.firebase.db().ref(`jobs/${this.props.id}`).on('value', (snap) => {
const job = {
id: snap.key,
...snap.val()
};
this.setState({
currentJob: job,
loading: false
})
});
const previousEntries = this.state.entries;
this.firebase.db().ref(`entries/${this.props.id}`).on('child_added', snap => {
previousEntries.push({
id: snap.key,
...snap.val()
});
this.setState({
entries: previousEntries
})
});
}
handleRemove() {
this.firebase.remove(this.props.id)
.then(() => {
this.setState({redirect: true})
})
};
pushLiveToClient() {
const updatedJob = {
...this.state.currentJob,
'lastPushedToClient': Date.now()
};
this.firebase.update(this.state.currentJob.id, updatedJob)
.then(() => this.handleSnackbarShow("Job pushed live to client"))
}
handleJobStatusChange() {
const newState = !this.state.currentJob.completed;
const updatedJob = {
...this.state.currentJob,
'completed': newState
};
this.firebase.update(this.state.currentJob.id, updatedJob)
}
handleSnackbarShow = (msg) => {
this.setState({
showSnackbar: true,
snackbarMsg: msg
});
};
handleSnackbarClose= (event, reason) => {
if (reason === 'clickaway') {
return;
}
this.setState({ showSnackbar: false });
};
handleAttachmentDialogClose =() => {
this.setState({attachmentDialogOpen: false})
};
handleClickOpen = (file) => {
this.setState({
attachmentDialogOpen: true,
openAttachment: file
});
};
handleImageGridShow(imageGrid) {
this.setState({selectedImageGrid: imageGrid})
}
handleImageGridClose() {
this.setState({selectedImageGrid: false})
}
handlePinnedImageShow(pinnedImage) {
this.setState({selectedPinnedImage: pinnedImage})
}
handlePinnedImageClose() {
this.setState({selectedPinnedImage: false})
}
handleMarkedImageLoaded() {
this.setState({markedImageLoaded: true})
}
render() {
const {classes} = this.props;
let {_, costPerItem} = calculateTotalPerProduct(this.state.entries);
if (this.state.redirect) {
return <Redirect to='/jobs' push/>
} else {
if (this.state.loading) {
return <Spinner/>
} else {
return (
<div className={styles.wrapper}>
{this.state.currentJob &&
<div>
<ViewJobActions currentJob={this.state.currentJob}
handleJobStatusChange={this.handleJobStatusChange}
pushLiveToClient={this.pushLiveToClient}
/>
<ViewJobDetails currentJob={this.state.currentJob}/>
<ViewCompanyDetails currentJob={this.state.currentJob}/>
<ViewClientsDetails currentJob={this.state.currentJob}/>
<ViewProductsDetails currentJob={this.state.currentJob}/>
{this.state.currentJob.selectedUploads && this.state.currentJob.selectedUploads.length > 0
? <ViewAttachmentDetails currentJob={this.state.currentJob} handleClickOpen={this.handleClickOpen}/>
: null}
<ViewEventLogDetails jobId={this.state.currentJob.jobId}
jobKey={this.state.currentJob.id}
entries={this.state.entries}
handlePinnedImageShow={this.handlePinnedImageShow}
handleImageGridShow={this.handleImageGridShow}/>
<ViewSummaryDetails stats={costPerItem}/>
<ViewJobAttachment open={this.state.attachmentDialogOpen}
handleRequestClose={this.handleAttachmentDialogClose}
attachment={this.state.openAttachment}
/>
{this.state.selectedImageGrid &&
<ImageGridDialog selectedImageGrid={this.state.selectedImageGrid}
handleRequestClose={this.handleImageGridClose}
handleClickOpen={this.handleClickOpen}
title="Pictures for job"
fullScreen={false}/>}
{this.state.selectedPinnedImage &&
<ViewPinnedImageDialog attachment={this.state.selectedPinnedImage}
open={!!this.state.selectedPinnedImage}
markedImageLoaded={this.state.markedImageLoaded}
handleMarkedImageLoaded={this.handleMarkedImageLoaded}
handleRequestClose={this.handlePinnedImageClose}
otherMarkedEntries={this.state.entries}
/>
}
<SimpleSnackbar showSnackbar={this.state.showSnackbar}
handleSnackbarClose={this.handleSnackbarClose}
snackbarMsg={this.state.snackbarMsg}/>
</div>}
</div>
);
}
}
}
}
export default withStyles(styles)(ViewJob);
You can define a regular component method and bind it in handler like this onSomething={this.handler.bind(this, index)} assuming you have some distinguishable thing in the index var
function should look like this
handler(index) {
...
}

Resources