Skip to content

Instantly share code, notes, and snippets.

@mickambar19
Last active March 25, 2019 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mickambar19/dbb172d2f6e230df585300dae8f0ef6b to your computer and use it in GitHub Desktop.
Save mickambar19/dbb172d2f6e230df585300dae8f0ef6b to your computer and use it in GitHub Desktop.
Example for react context
import React, { Component, Fragment } from 'react'
import PropTypes from 'prop-types'
const FormContext = React.createContext()
const Step1 = () => {
return (
<div>
General Step:
<FormContext.Consumer>
{({ form: { title, numero, otro }, onChange }) => (
<Fragment>
<input
type="text"
onChange={onChange}
value={title}
name="title"
placeholder="title"
/>
<input
type="text"
onChange={onChange}
value={numero}
name="numero"
placeholder="numero"
/>
<input
type="text"
onChange={onChange}
value={otro}
name="otro"
placeholder="otro"
/>
</Fragment>
)}
</FormContext.Consumer>
</div>
)
}
const Step2 = () => {
return (
<div>
Location Step:
<FormContext.Consumer>
{({ form: { state, city, address }, onChange }) => (
<Fragment>
<input
type="text"
onChange={onChange}
value={state}
name="state"
placeholder="state"
/>
<input
type="text"
onChange={onChange}
value={city}
name="city"
placeholder="city"
/>
<input
type="text"
onChange={onChange}
value={address}
name="address"
placeholder="address"
/>
</Fragment>
)}
</FormContext.Consumer>
</div>
)
}
export default class UploadDevelopment extends Component {
static propTypes = {
prop: PropTypes
}
state = {
currentStep: 0,
formValues: {
title: '',
numero: '',
otro: '',
state: '',
city: '',
address: ''
}
}
renderStep = () => {
const { currentStep } = this.state
switch (currentStep) {
case 0:
return <Step1 />
case 1:
return <Step2 />
default:
break
}
}
backButton = () => {
this.setState(prevState => ({
currentStep:
prevState.currentStep - 1 >= 0 ? prevState.currentStep - 1 : 0
}))
}
nextButton = () => {
this.setState(prevState => ({
currentStep:
prevState.currentStep + 1 <= 1
? prevState.currentStep + 1
: prevState.currentStep
}))
}
onChange = e => {
const {
target: { value, name }
} = e
this.setState(prevState => ({
formValues: {
...prevState.formValues,
[name]: value
}
}))
}
render() {
return (
<div>
This is before provider
<FormContext.Provider
value={{
form: this.state.formValues,
onChange: this.onChange
}}
>
{this.renderStep()}
<button onClick={this.backButton}>Atrás</button>
<button onClick={this.nextButton}>Siguiente</button>
<button onClick={() => alert(JSON.stringify(this.state.formValues))}>
Submit
</button>
</FormContext.Provider>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment