Skip to content

How to inject a dinamically created element into an existing div in React JSX?

I have a list of objects photos, from a json data file, that I would like to organize into 3 different <div> columns, but I dont know how to achieve that, here is my broken non-optimized code:

<div className="container">
    <div ref={leftColRef} className="left-col" />
    <div ref={centreColRef} className="centre-col" />
    <div ref={rightColRef} className="right-col" />
    {Object.keys(photos).forEach((n, i) => {
        const id = photos[n].id;
        const thumb = photos[n].thumbnailUrl;
        const title = photos[n].title;
        const element = (
            <Thumbnail id={id} title={title} thumb={thumb} />
        if (i % 3 === 0) {
        } else if (i % 3 === 1) {
        } else {
        // this line works, it idsplays the data but is commented as the data needs to go inside its respective columns
        // return <Thumbnail key={id} title={title} thumb={thumb} />;

The idea is to insert some elements into the left-column when i%3 = 0 and others in the centre-column when i%3 = 1 and so on …

And a link to my codesandbox

Any help/advise will be much appreciated.



Easiest is probably to prepare the data outside the render function and to render the column one by one.

You should not manipulate the DOM like it’s done in jQuery using JSX


const Component = (props) => {
    const filterPhotos = (column) => {
        return,index)=> index%3==column);

    return <>
        <MyColumn photos={filterPhotos(0)}/>
        <MyColumn photos={filterPhotos(1)}/>
        <MyColumn photos={filterPhotos(2)}/>
User contributions licensed under: CC BY-SA
3 People found this is helpful