Dynamically create Content React

822 Views Asked by At

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 >
    }
2

There are 2 best solutions below

5
Zayco On BEST ANSWER

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;
1
ggorantala On

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>

        );
    }