简体   繁体   中英

How do I pass object from array within one component?

Const App references two other components above it. At run time, it compiles successfully with no errors but I'm not getting the result I want.

Inside const App = () => {}, I have no problems rendering the Header tag within the return statement. In fact, it does what I want it to do which is to print "Half Stack application development" as a header in html.

The problem is with the Total tag underneath it. Underneath the header I want to render the number 342 as a paragraph tag onto the web page, but its not working.

Any help would be greatly appreciated to a newbie like me who just started learning React. Thank you :)

// Header takes care of rendering the name of the course.

const Header = (props) => { 
    return (
        <div>
            <h1>{props.course}</h1>        
        </div>
    )
}
// Total renders the total amount of exercises.

const Total = (props) => {
    return (
        <div>
            <p>Total number of exercises:{props.parts}</p>
        </div>
    )
}

// Header takes care of rendering the name of the course.

const App = () => {
    const course = {
        name: 'Half Stack application development' , 
        parts: [{name:'One' , exercises:342}]

      }

    return (
        <div>
            <Header course={course.name} />
            <Total parts={course.parts.exercises} /> 

            {/* 
            <Content parts={parts} />
            */}

        </div>
    )
} 

ReactDOM.render(<App />, document.getElementById('root'))

This is not really a react problem but a problem with accessing the parts array :

Try:

<Total parts={course.parts[0].exercises} /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM