How to render random objects from an array in React?
I went ahead and created a working example for you
import React from 'react';
import { Link } from 'react-router';
function shuffleArray(array) {
let i = array.length - 1;
for (; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
class RecommendedPosts extends React.Component {
render() {
const shuffledPosts = shuffleArray(this.props.posts);
return (
<ul>
{shuffledPosts.map((post) => {
return (
<li key={post.id}>
<p>{post.title}</p>
<p>{post.text}</p>
<p>{post.category}</p>
<Link to={`/blog/post-1/:${post.id}`}>Weiter lesen</Link>
</li>
);
})}
</ul>
);
}
}
RecommendedPosts.propTypes = {
posts: React.PropTypes.array,
};
export default RecommendedPosts;
Bonus tip - since you're not using state or lifecycle, you can create a much simpler functional component as such:
import React from 'react';
import { Link } from 'react-router';
function shuffleArray(array) {
let i = array.length - 1;
for (; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function RecommendedPosts({ posts }) {
const shuffledPosts = shuffleArray(posts);
return (
<ul>
{shuffledPosts.map((post) => {
return (
<li key={post.id}>
<p>{post.title}</p>
<p>{post.text}</p>
<p>{post.category}</p>
<Link to={`/blog/post-1/:${post.id}`}>Weiter lesen</Link>
</li>
);
})}
</ul>
);
}
RecommendedPosts.propTypes = {
posts: React.PropTypes.array,
};
export default RecommendedPosts;
In your Recommended post first shuffle the posts and store it in state and then render
import React from 'react';
import { Link } from 'react-router';
class RecommendedPosts extends React.Component {
constructor() {
super(props);
this.state = {
posts: this.shuffle(this.props.posts)
}
}
shuffle(posts){
///shuffle using some algo
return posts
}
render() {
return (
<ul>
{this.state.posts.map((post, idx) => {
return (
<li key={idx}>
<p>{post.title}</p>
<p>{post.text}</p>
<p>{post.category}</p>
<Link to={`/blog/post-1/:${post.id}`}>Weiter lesen</Link>
</li>
);
})}
</ul>
);
}
}
RecommendedPosts.propTypes = {
posts: React.PropTypes.array,
};
export default RecommendedPosts;