I have two arrays, one with urls and one with content. They look like this:
const link = [ 'www.test0.com', 'www.test1.com', 'www.test2.com' ]
const content = [ 'this is test0 content', 'this is test1 content', 'this is test2 content' ]
How can I map over both arrays at the same time and use their value in my newly created element?
I need to use the value of the url for my reactplayer and the the value of the content as the text underneath the player.
So it should look something like this:
<Reactplayer url"link0" />
<ControlLabel>content0</ControlLabel>
Is this possible? And what would be a better way of setting this up?
Using the second parameter of map
, which is the index of the current element, you can access the correct element of the second array.
const link = [ 'www.test0.com', 'www.test1.com', 'www.test2.com' ];
const content = [ 'this is test0 content', 'this is test1 content', 'this is test2 content' ]
const players = link.map((value, index) => {
const linkContent = content[index];
return (
<div>
<Reactplayer url="{value}" />
<ControlLabel>{linkContent}</ControlLabel>
</div>
);
});
This is the perfect candidate for the zip
method which is available with various libraries, such as Lodash or Rambda, if you have one of those in your project.
const players = _.zip(link, content).map((value) => {
return (
<div>
<Reactplayer url="{value[0]}" />
<ControlLabel>{value[1]}</ControlLabel>
</div>
);
});
You would be better off having it as:
const data = [
{ link: "www.test0.com", text: "this is test0 content" },
{ link: "www.test1.com", text: "this is test1 content" }
];
You would then render content like:
render() {
var links = [];
for (var i = 0; i < data.length; i++) {
var item = data[i];
links.push(<div><Reactplayer url={item.link}/><ControlLabel>{item.text}</ControlLabel></div>);
}
return (<div>{links}</div>);
}
Please note, this is untested code as I don't have a JSX project currently setup that I can test it in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With