Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

javascript - ReactJS How to render 4 items in a row (items from api)

I am retrieving a list of posts from my API and i'd like to arrange them such as ->

<Row>
    <Col><Card.......></Col>
    <Col><Card.......></Col>
    <Col><Card.......></Col>
    <Col><Card.......></Col>
<Row>

I've looked around and found some examples, but i am either too "new" to ReactJS or they simply do not work in my case.

This is how my class looks at the moment ->

class ApiPosts extends Component {
    constructor() {
        super();
        this.state = {
            blogPosts: [],
        };
    }

    componentDidMount() {
        const { classes } = this.props;

        fetch('http://localhost:53595/api/public/posts', {
            method: 'get',
        })
            .then(results => {
                return results.json();
            }).then(data => {
                let blogPosts = data.map((post, index) => {
                    if (post.type === "News") {
                        if ((index % 4) === 0) {
                            return (
                                <Col xs >
                                    <Card className={classes.card} key={post.id}>
                                        <CardActionArea>
                                            <CardMedia
                                                component="img"
                                                alt={post.title}
                                                className={classes.media}
                                                height="140"
                                                image={post.imageName}
                                                title={post.title}
                                            />
                                            <CardContent>
                                                <Typography gutterBottom variant="headline" component="h2">
                                                    {post.title}
                                                </Typography>
                                                <Typography component="p">
                                                    {post.body}
                                                </Typography>
                                            </CardContent>
                                        </CardActionArea>
                                        <CardActions>
                                            <Button size="small" color="primary">
                                                Share
                                            </Button>
                                            <Button size="small" color="primary">
                                                Learn More
                                    </Button>
                                        </CardActions>
                                    </Card>
                                </Col>
                            )
                        }
                    }
                });
                this.setState({ blogPosts: blogPosts });
                //console.log("state", this.state.blogPosts);
            })
    }
    render() {

        return (
            <React.Fragment>
                <Col xs />
                {this.state.blogPosts}
            </React.Fragment>

        )
    }
}

Is there any way to achieve this using map ? Sorry for my newbie question, still learning ReactJS. Many thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, group the items based on row where they will be placed, then iterate over the grouped data and render 4 items per row. Please consider following code snippets

Creating group data using reduce method

componentDidMount() {
  ...
  .then(data => {
     var grouped = data.reduce((acc, post, ind) => {
       var index = parseInt(ind / 4);
       acc[index]= acc[index] || []; 
       acc[index].push(<Col > /*Column definition goes here*/ </Col>);
       return acc;
     }, {});
     this.setState({ grouped });
  });
}

Once you have the grouped data, you can render it as follows

render() {
  const { grouped } = this.state;
  return (
    <React.Fragment>
      {
        Object.keys(grouped).map(row => {
          return (
            <Row>
            {
              grouped[row]
            }
            </Row>
          );
        })
      }
    </React.Fragment>
  );
}

Hope this will help!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...