0

Let's say I have a list of fields that I want to access on a props I'll be passing to that Component.

The code below does not work, but is it possible to access some prop value as: {session['myCustomKey']}?

class MyComponent extends React.Component {

  render() {
    const { myObj } = this.props;
    const fields = ['field_1', 'field_2', 'field_3'];

    return (
      <div className={'row'}>
        {fields.map((field) =>
          <div className={'col-sm-4'}>
            <div className={'row'}>
              <InputText
                id={`{${myObj} + ${field}`}
                value={`${myObj} + "." + ${field}`}
                isDisabled
              />
            </div>
          </div>
      )}
      </div>
    );
  }
}
panosl
  • 1,709
  • 2
  • 12
  • 15
  • 2
    it should work: `{session['myCustomKey']}` are you facing any issue in this ? instead of "value={`${myObj} + "." + ${field}`}" use `value={myObj[field]}`. – Mayank Shukla May 02 '17 at 16:40
  • @MayankShukla I need to be able to combine the mapping of the field somehow {myObject[{field}]} or something like that. – panosl May 02 '17 at 16:43
  • FWIW, the problem (and solution) has nothing to do with React or JSX. – Felix Kling May 02 '17 at 16:50

1 Answers1

2

props is an object, we can access the values by props.data['key'].

Check this example:

var App = ({data}) => {
   let fields = ['a', 'b', 'c'];
   return(
     <div>
        {
           fields.map(el=> <p> {data[el]} </p>)
        }
     </div>
   )
}

let data = {'a': 1, 'b': 2, 'c': 3};

ReactDOM.render(<App data={data}/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>

But i think defining the keys in a separate array is not required, if you want to iterate the props data (passed from parent) then you can use it like this also:

Object.keys(this.props.myObj).map(el => {
    return <p key={el} > {el}: {this.props.myObj[el]} </p>
})
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
  • Yup, that works just fine. I added the array as dummy code, the actual fields will be passed depending on the object type that's being selected. I'll be able to accept your answer in a bit. Thanks again. – panosl May 02 '17 at 16:53
  • glad, it worked for you :) – Mayank Shukla May 02 '17 at 16:54
  • You know if it's possible to access a second level of the object somehow? like {myObj[a][b]} but with {myObj[a.b]} or something similar? – panosl May 03 '17 at 15:59
  • `{myObj[a][b]}` will work but need to check also whether that exist or not otherwise it will throw the error. – Mayank Shukla May 03 '17 at 16:09