0

I am new on this forum and new in React Native. Could someone write me a piece of code to create form elements (image, toggle switch) based on json.

My JSON look like

[{ "consumer": "S1", "status": "False"},{ "consumer": "S2", "status": "False"},{"consumer": "S3", "status": "True"},{ "consumer": "S4", "status": "False"},{ "consumer": "S7", "status": "False"}]

I would like to get i for each mode something like:

<View style={{width: '30%', height: 200}}>
          <Image
            source={
              require('../assets/images/s1.png') //sx
            }
            style={styles.welcomeImage}
          />

        </View>
        <View style={{width: '30%', height: 200}}>
          <Switch
            //here get status of s1..s8
        </View>

1 Answer 1

2

You should map through the array. Something like this:

render() {
  var consumers = [{ "consumer": "S1", "status": "False"},{ "consumer": "S2", "status": "False"},{"consumer": "S3", "status": "True"},{ "consumer": "S4", "status": "False"},{ "consumer": "S7", "status": "False"}];
  return (
    {consumers.map((c, i) => {
      return [
        <View style={{width: '30%', height: 200}}>
          <Image
            source={require('../assets/images/' + c.consumer + '.png')}
            style={styles.welcomeImage}
          />
        </View>
        <View style={{width: '30%', height: 200}}>
          <Switch value={c.status} />
        </View>
      ]
    })}
  );
}
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks Brian but what is the easiest way to read this JSON to consumers variable and on what position, my JSON is actualy on link
Do you want to read the JSON in from an API call? If you're getting it from elsewhere I'd recommend getting the JSON in componentDidMount() and using setState to store it in your component state and then mapping that instead of a variable in the render function.
Or pass the JSON down as a prop from the parent component.
Wow Brian, you are so fast! Can you pass me a chunk of code beacuse I am still floating insecure in this waters :D
Thanks, Endi. I can, but I'm still not sure how you're getting the JSON. Is it hard-coded, are you getting it from an external source, is it being passed down from a parent?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.