0

Okay so I have a react-app which has a component which looks like this

import { TimeLine, Monday, Tuesday, Wednesday, Thursday, Friday } from './WorkSchedComponents';



class WorkSched extends Component {
            render() {
                return(
                    <div>
                        <div className='header'>
                        <h1>Schedule</h1>
                        </div>
                        <Container>
                            <Row>
                                <div className='timeline'><TimeLine /></div>
                                <div className='data-class'><Monday /></div>
                                <div className='data-class'><Tuesday /></div>
                                <div className='data-class'><Wednesday /></div>
                                <div className='data-class'><Thursday /></div>
                                <div className='data-class'><Friday /></div>
                            </Row>
                        </Container>
                    </div>
                );
        }
}

Here I am adding all days components one by one. Is there any way I can use a loop to add these components, maybe use map?

1

1 Answer 1

2

Something like:

[Monday, Tuesday, Wednesday, Thursday, Friday]
     .map(component => <div className='data-class'><component/></div>);

eg.

<Container>
    <Row>
        {
        [Monday, Tuesday, Wednesday, Thursday, Friday]
            .map(component => <div className='data-class'><component/></div>);
        }
    </Row>
</Container>

You should add a key to the div as well, to help React identify when things changed.


As a side note, your approach of having a separate component for each day seems suboptimal. What about having one Day component and passing in the day as a prop?

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the suggestion, I think having one Day component will be much better!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.