Skip to content

Instantly share code, notes, and snippets.

@SergProduction
Created April 3, 2018 20:39
Show Gist options
  • Save SergProduction/2266b4a2c099065a85f3ab5b6f31b3ef to your computer and use it in GitHub Desktop.
Save SergProduction/2266b4a2c099065a85f3ab5b6f31b3ef to your computer and use it in GitHub Desktop.
class GenForm {
static propTypes = {
type: pt.oneOf(['checkbox', radioButton]).isRequared,
description: pt.string,
radioOptions: pt.arrayOf(pt.shape({
name: pt.string,
description: pt.string,
})),
}
state = {
checkbox: '',
radioButton: '',
}
handleCheckbox = (event) => {
this.setState({checkbox: !event.target.checked})
}
handleRadioButton = (event) => {
this.setState({radioButton: event.target.name})
}
renderCheckbox = () => (
<input
type="checkbox"
checked={this.state.checkbox}
onChange={this.handleCheckbox}
>
)
renderRadioButton = () => (
<div onChange={this.handleRadioButton}>
{this.props.radioOptions.map(opt => (
<input
type="radio"
name={opt.name}
value={opt.name}
checked={opt.name === this.state.radioButton}
>
{opt.decription}
</input>
))}
</div>
)
render() {
const { type } = this.props
if (type === 'checkbox') return this.renderCheckbox()
if (type === 'radioButton') return this.renderRadioButton()
}
}
const api = () => new Propmise((res) => {
res([
{
type: 'radioButton',
radioOptions: [
{name: 'Gender', description: 'ПОЛ'}
{name: 'name', description: 'ИМЯ'}
],
},
{
type: 'checkbox',
description: 'Вы согласны принять условия?'
}
])
})
class GetData {
state = {
data: null
}
didMount() {
api.get()
.then(data => this.setState({data}))
}
render() {
const { data } = this.state
if (data) return null
return data.map(form => (
<GenForm
type={form.type}
radioOptions={form.radioOptions}
description={form.description}
/>
))
}
}
@dmitryshelomanov
Copy link

class Test extends Component {
state = {
data: {},
isReady: false,
}

componentDidMount() {
const { actions } = this.props
let result = {}

for (let i = 0; i < actions.length; i++) {
  const { name, items } = actions[i]

  result[name] = {}
  for (let j = 0; j < items.length; j++) {
    const { value } = items[j]

    result[name][value] = false
  }
}

this.setState({ data: result, isReady: true })

}

render() {
const { actions } = this.props

if (!this.state.isReady) {
  return null
}

return(
  actions.map((item) => (
    <div>
      {item.items.map((field) => (
        <React.Fragment>
          {field.value}
          <input
            type="radio"
            checked={this.state.data[item.name][field.value]}
          />
        </React.Fragment>
      ))}
    </div>
  ))
)

}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment