CoderLBY
CoderLBY

Reputation: 89

How to create a child component inside a component and render them accordingly?

I have a root App that contains"Content" component, but now I wish to create three "Part" child component inside "Content". How should I do it ?

const Content = (props) => {
  return (
    <div>
      <p>{props.part} {props.exercise}</p>
    </div>
  )

const App = () => {
  const course = 'Half Stack application development'
  const part1 = 'Fundamentals of React'
  const exercises1 = 10
  const part2 = 'Using props to pass data'
  const exercises2 = 7
  const part3 = 'State of a component'
  const exercises3 = 14

  return (
    <div>
      <Header course={course} />
      <>Content:</>
      <Content part={} exercise={}/>
      <>Total:</>
      <Total exercise={exercises1 + exercises2 +exercises3} />
    </div>
  )
}

Not completely sure, but this is the exmaple, I got

const Content = ... {
  return (
    <div>
      <Part .../>
      <Part .../>
      <Part .../>
    </div>
  )
}

Question again: Refactor the Content component so that it does not render any names of parts or their number of exercises by itself. Instead it only renders three Part components of which each renders the name and number of exercises of one part.

Upvotes: 1

Views: 173

Answers (1)

Amila Senadheera
Amila Senadheera

Reputation: 13265

You can keep the data of each part in an array and use map to render it. This is a normal pattern of doing it.

Try like this

import React from "react";

const Content = ({ content }) => {
  return (
    <div>
      <p>
        {content.part} {content.exercise}
      </p>
    </div>
  );
};

const App = () => {
  const course = "Half Stack application development";

  const contents = [
    { part: "Fundamentals of React", exercise: 10 },
    { part: "Using props to pass data", exercise: 7 },
    { part: "State of a component", exercise: 14 }
  ];

  return (
    <div>
      <Header course={course} />
      <>Content:</>
      {contents.map((content) => (
        <Content content={content} />
      ))}
      <>Total:</>
      <Total exercise={exercises1 + exercises2 + exercises3} />
    </div>
  );
};

export default App;

Code sandbox

Upvotes: 1

Related Questions