UPDATE:
For anyone learning and confused on this as I was, this page describes what’s going on — my confusion was between a React component vs React elements https://reactjs.org/docs/rendering-elements.html
ORIGINAL QUESTION:
The page linked below suggests the children
prop is passed by default when using FunctionComponent
, however it doesn’t seem to work for me. Given the following case, props.children
is undefined. I’m still picking up React — what am I doing wrong?
import React, { FunctionComponent } from "react" type Props = { myProp: string } const Nav: FunctionComponent<Props> = (props) => { console.log(props.myProp, props.children) return ( <main> <nav> <a href="foo">FOO</a> <a href="bar" className="active">BAR</a> </nav> </main> ) } // This component is rendered from within another component, e.g. `return (<div><Nav /></div>)
My end goal is to access a child attribute somehow. The active
class, for example.
source: https://fettblog.eu/typescript-react/children/
Advertisement
Answer
props.children === undefined
because you’re rendering
<div> <Nav /> </div>
and <Nav />
has no child element in it.
If you change it to something like
<Nav myProp="Hello"> World! </Nav>
then console.log(props.myProp, props.children)
will print “Hello World!” in the console.