I have a question about React and JSX.
The main component code below works correctly:
function App(){
return (
<Hello />
)
}
Then I define a function component and call a function inside it. Why does it not work?
function Hello(){
f();
}
function f(){
return(<h1>hello</h1>);
}
Whereas this does work:
function Hello(){
return(<h1>hello</h1>);
}
To elaborate on other answers, you should refer to the example in the React docs:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element.
So, as others have said, your best bet is to return a React element (via JSX, presumably, but can call other components as you're trying):
// Using conventional function syntax
function Hello(){
return f();
}
// Using arrow functions and implicit returns
const Hello = () => f();
Change
function Hello(){
f();
}
to
function Hello(){
return f();
}
Without the return keyword, Hello()
's return value is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With