0

I have two components in my project, the First component is App I got this App component when I created a project. And Second Component is ClassRoom. Now in App.js, I have an array, In that array, I have four different names. Now I have to pass those four names for my child component that is ClassRoom. I know how to loop an Array of objects to React. But I don't know how to loop Array and pass that array to child component so help me to achieve this task.

This is App.js

import React from 'react';
import './App.css';
import ClassRoom from './ClassRoom/ClassRoom';

function App() {
  const students = ['shiva', 'krishna', 'ram', 'madhav']
  return (
    <div className="App">
     <ClassRoom></ClassRoom>
    </div>
  );
}

export default App;

This is App.css

.App {
  text-align: center;
}

.App-logo {
  height: 40vmin;
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #09d3ac;
}

This is ClassRoom.js

import React, { Component } from 'react'
import './ClassRoom.css'

export default class ClassRoom extends Component {
    render() {
        return (
            <div>

            </div>
        )
    }
}

This is ClassRoom.css

There is no css in ClassRoom.css

My expected output is I need to pass students Array from Parent Component which is App.js to Child Component which is ClassRoom.js. If not, clear with my doubt, please put a comment.

3 Answers 3

7

Just do <ClassRoom students={students}/>

And in ClassRoom componenets access it using this.props.students

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

Comments

1

In App.js

function App() {
  const students = ['shiva', 'krishna', 'ram', 'madhav']
  return (
    <div className="App">
     <ClassRoom studentsArray = { students } />
    </div>
  );
}

In ClassRoom.js

export default class ClassRoom extends Component {
    render() {
        return (
            <div>
              <ul>
               {this.props.studentsArray.map( student => `<li> ${student} </li>` )}
             </ul>
            </div>
        )
    }
}

Comments

0

If your ClassRoom component is functional component, then use this.

<ClassRoom students={students}/>

 function ClassRoom(props) {
    render() {
        return (
            <div>
                {props.students}
            </div>
        )
    }
}

export default ClassRoom;

In functional component use props.students and in class component use this.props.students

Comments

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.