0

In my React project, I need to add rows dynamically.

I code I use to do it as follows

    let Para=GetPara();
    React.createElement("p", { style: { color: "black" } }, Para[0]),
    React.createElement("p", { style: { color: "black" } }, Para[1])

In the above code Para is populated by a ajax function which returns an array I would like to do it dynamically like

function GetPara() {
    return (
    for (let index = 0; index < Para.length; index++) {
        React.createElement("p", {style: {color: "black"}}, Para[i])
    }
}

But In the above function I can't seem to return a react element. I also tried

function GetPara() {
    let teststr = "";
    for (let index = 0; index < Para.length; index++) {
        teststr += React.createElement("p", , Para[i]);
    }
    return (teststr);
}

If I use the above method the value is returned is string and appears as

"<p>test1</p><p>test2</p>"

Based on the answer I changed the code below but i still don't get the values

and get the following error Uncaught (in promise) TypeError: B.setState is not a function

  const Questions = (props) => {

    let Qvalues = [];
 GetData().then((response => {
            if (response) {
                QuestionValues = response;
                if (QuestionValues && QuestionValues.length > 0) {
                    console.log(QuestionValues.length);
                    for (let index = 0; index < QuestionValues.length; index++) {
                        let Qoptions = QuestionValues[index]["Options"].split(',').map(function (val)
                         {             return { key: val, text: val };
                        }
                        );
                        Qvalues.push(<div className={styles.FormRow}>
                            <p>Qoptions[0] </p>
                            <p>Qoptions[1] </p>
                        </div>);

                    };


                };
            };
            this.setState({QuestionValues:Qvalues});   console.log(Qvalues);
})).then(res => {
    return (

        <div >
            { this.state.QuestionValues&& Qvalues}
        </div>
    )
});

return (
    <div >
        {Qvalues}
    </div>
)
 public render(): React.ReactElement<IEProps> {

        return
                <div>
                    <div className={styles.container}>
                    <Header></Header>
                    <Questions></Questions>
                    <Footer></Footer>
                    </div>
              </div>


    }

Finally i mananged to fix the issue with valuable answers from Zayco and gopigorantala.

My solution is as follows

  public componentDidMount() {
    let Qvalues = [];
    GetData().then((response => {
        if (response) {
            QuestionValues = response;
            if (QuestionValues && QuestionValues.length > 0) {
                console.log(QuestionValues.length);
                for (let index = 0; index < QuestionValues.length; index++) {
                    let Qoptions = QuestionValues[index]["Options"].split(',').map(function (val) { return { key: val, text: val }; });
                    Qvalues.push(<div className={styles.FormRow}>
                        <p>Qoptions[0] </p>
                        <p>Qoptions[1] </p>
                    </div>);

                };
            };
            this.setState({ QuestionValues: Qvalues });
        };
    }))
}
 public render(): React.ReactElement < IEProps > {
    const Questions = (props) => {

        return (
            <div>
                {this.state.QuestionValues}
            </div>)
    }
        return
        <div>
                    < div className = { styles.container } >
    <Header></Header>
    <Questions></Questions>
    <Footer></Footer>
                    </div >
              </div >
    }
user1339913
  • 1,017
  • 3
  • 15
  • 36

2 Answers2

0

You can do this in the render() method of react..

I am using JSX syntax in below..

ex: lets say I have a persons object with data, please see this is a sample data and you should be pulling this data through rest api or from a database..

state = {
        persons: [
            {id: '01', name: 'one', age: 28},
            {id: '02', name: 'two', age: 26}
        ]
    };

// following persons are rendered dynamically based on the state object count..

render() {
        let persons = (
            <div>
                {this.state.persons.map((person, index) => {
                    return (<div className="Person">
                        <p>I'm a {person.name} and I am {person.age} years old</p>
                    </div>)
                })
                }
            </div>
        );

        return (
            <div className="App" >
                {persons}
            </div>

        );
    }
ggorantala
  • 196
  • 2
  • 16
  • Thank you for the answer. I tried the answer but Persons is null for me as I get the person.name and person.age using a promise . – user1339913 Jan 27 '19 at 19:42
0

Provided that your api call returns an array of strings this should work.

import React, { Component } from 'react';
import { View, Text } from 'react-native';

class Questions extends Component {
  state = {
    questionValues: null,
  };

  componentDidMount() {
    GetData().then(response => {
      if (response) {
        if (response.length > 0) {
          this.setState({
            questionValues: response,
          });
        }
      }
    });
  }

  renderQuestions = () => this.state.questionValues.map(q => <Text key={q}>{q}</Text>);

  render() {
    if (!this.state.questionValues) return <Text>Here you can return a custom loading component</Text>;

    return <View>{this.renderQuestions()}</View>;
  }
}
export default Questions;
Zayco
  • 327
  • 4
  • 14
  • thank you for the answer i updated the question based on your answer but i am still not getting the paragraph to appear. – user1339913 Jan 28 '19 at 12:26
  • I'll update my answer after work. Just to clarify. Does the list of questions get updated after the first api call, or is the list static after the first api call? And can you give an example of the response? – Zayco Jan 28 '19 at 14:46
  • The list of questions are loaded once and do not change after wards. – user1339913 Jan 28 '19 at 15:09
  • I updated the answer. I tested this out and it works granted that getData() return an array of strings. – Zayco Jan 28 '19 at 16:32
  • I get an error trying to import react-native. I however managed to fix the issue. I needed to declare the const Questions inside the render function as render fires after componentDidMount function. – user1339913 Jan 28 '19 at 18:09