0

I'm new to React. I currently have a component. This component has a title and a body. The body can have several paragraphs and I want to dynamically add the elements depending on how many paragraphs each has. So right now I have this:

import React from 'react';

class Content extends React.Component{
    render(){
        var props_list = this.props;
        var keys = Object.keys(props_list);
        console.log(props_list["title"]);

        for (var i = 0; i < keys.length; i++){
            console.log(props_list[keys[i]]);
        }

        return (
            <div className="introduction">
                <h3>{props_list["title"]}</h3>
                <div className="div-content">

                </div>
            </div>
        );
    }
}

export default Content; 

Now with this code I can get all the props and information that it's added to each component but I have no clue how to add this information dynamically into the div-content.

Thank you in advance!

2
  • 1
    It is not clear what you want each paragraph to look like, or what collection of things you want to display. Are you trying to display each of the non-title props and their values? Commented Dec 21, 2019 at 1:23
  • You can render an array of html elements, components, and primitives Commented Dec 21, 2019 at 1:24

1 Answer 1

1

So. If we could know more about the shape of the props passed into this component it would help but this should be enough to get you going.

import React from 'react';

class Content extends React.Component{
   render(){
    var props_list = this.props;
    var keys = Object.keys(props_list);
    console.log(props_list["title"]);
            const paragraphs = [];
    for (var i = 0; i < keys.length; i++){
        console.log(props_list[keys[i]]);
        // This part is to make sure you are not re-rendering your title.
        if(keys[i] !== "title"){
            paragraphs.push(<p>{props_list[keys[i]]}</p>);
        }      
    }

    return (
        <div className="introduction">
            <h3>{props_list["title"]}</h3>
            <div className="div-content">
              {paragraphs}
            </div>
        </div>
    );
 }
} 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much. This works perfectly however you have to add {props_list[keys[i]]} or it won't render as a variable.
excellent. Glad it worked. I'll edit the above.

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.