Reputation: 124
I want to generate a prop for each of the paragraph created.
var TabContent = React.createClass({
render: function(){
var paragraph = [];
for (var i = 0; i < this.props.nrPar; i++) {
var x = "p" + i; //or can I use a variable after this.props.?
paragraph.push(<p key={i}>{this.props.p + i}<br></br></p>);
}
return(
<div>
{paragraph}
</div>
);
}
});
ReactDOM.render(
<TabContent nrPar="3"
p1="first paragraph of text"
p2="second paragraph of text"
p3="third paragraph of text"/>
,month
)
I want to be able to choose the amount of paragraphs I want to create and be able to write text in each of them.
nrPar is the number of paragraphs that I want to be created.
p1, p2, p3 are the result of nrPar because I want 3 paragraphs for now.
Upvotes: 0
Views: 51
Reputation: 3234
That seems to be a bit of an antipattern to me. The easiest way would probably be just to pass an array of strings as a prop.
If you need to do something with the paragraph count, just get the array length like so:
const TabContent = props => (
<div>
<p>count: {props.paragraphs.length}</p>
{props.paragraphs.map((paragraph, index) => (
<p key={index}>{paragraph}</p>
))}
</div>
);
ReactDOM.render(
<TabContent paragraphs={["first", "second"]} />,
document.querySelector("#root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Upvotes: 1
Reputation: 329
In ReactJs
you can pass arrays as props. Modified your code little bit.
var TabContent = React.createClass({
render: function () {
var paragraph = [];
for (var i = 0; i < this.props.paragraphs; i++) {
paragraph.push(<p key={i}>{this.props.paragraphs[i]}<br></br></p>);
}
return (
<div>
{paragraph}
</div>
);
}
});
ReactDOM.render(
<TabContent
paragraphs={[
`first paragraph of text`,
`second paragraph of text`
]}
/>
, month
)
Upvotes: 3