Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In React why does calling a function from another function in our code not work and display?

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>);
 }
like image 365
reza n Avatar asked Oct 07 '19 17:10

reza n


2 Answers

Functional Components must return React Components of some form

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();
like image 109
Martin Avatar answered Sep 29 '22 22:09

Martin


Change

function Hello(){
    f();    
}

to

function Hello(){
    return f();    
}

Without the return keyword, Hello()'s return value is undefined.

like image 43
Jeff Hechler Avatar answered Sep 29 '22 22:09

Jeff Hechler