samedi 1 juillet 2017

Rendering multiple items with different props React ES6

I am trying to create a field of material ui checkboxes.

I know I could do

<div style=>
      <Checkbox style= checked= onCheck= key={"one"} label={"one"} iconStyle= />
      <Checkbox style= checked= onCheck= key={"two"} label={"two"} iconStyle= />
      .
      .
      .
</div>

for however many checkboxes I need. This however gets annoying and involves a lot of writing.

Therefore I have a CheckboxesFields class which maps Checkboxes based on a prop called labelsList, which contains a list of type String

import React from 'react'
import Checkbox from 'material-ui/Checkbox'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'

const CheckboxesField = props => {
  const checkboxes = props.labelsList.map(label => <Checkbox style= key={label} label={label} iconStyle= />)
    return (
      <MuiThemeProvider>
        <div style=>
          {checkboxes}
        </div>
      </MuiThemeProvider>
    )
  }

export default CheckboxesField

This is then called in App.js

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import CheckboxesField from './CheckboxesField'

class App extends Component {
  render() {
    return (
      <div className="App">
        <CheckboxesField labelsList={["1", "2", "3", "4", "5"]} />
      </div>
    )
  }
}

export default App
ReactDOM.render(<App />, document.getElementById('root'))

This works but unlike the first example if I pass the props onCheck and checked it will apply to every single checkbox. However I want each checkbox to be controlled individually.

How would I go about doing this?

Thanks for your help.




Aucun commentaire:

Enregistrer un commentaire