Captai-N
Captai-N

Reputation: 1502

How can I display a constant function within my return method with React?

I am trying to display a constant within a return. The constant is a function and is itself in an export function. Now when I try to display the constant in the return method after checking a condition, I get an error. First check ("home") is working. But all other not

const [panel, setPanel] = React.useState("home");

function whichPanel(wert) {
 setPanel(wert);
}

const ansicht = () => {
 <h1>{panel</h1>;
};

 return (
 <>
  [...]
      <Row className="justify-content-center">
    {panel === "home" ? (
      sucht ? (
        <Loading></Loading>
      ) : (
        ergebnis.map((pep, index) => {
          return (
            <Col
              key={index}
              md={3}
              xs="auto"
              sm={12}
              style={{ marginTop: "40px" }}
            >
              <Card pep={pep}></Card>
            </Col>
          );
        })
      )
    ) : panel === "admin" ? (
      <> {ansicht}</>
    ) : panel === "einstellungen" ? (
      <> {ansicht}</>
    ) : panel === "favoriten" ? (
      <> {ansicht}</>
    ) : (
      ""
    )}
  </Row>
 </>

 )

I got this error:

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.

Upvotes: 0

Views: 35

Answers (2)

SILENT
SILENT

Reputation: 4258

Couple possible mistakes. FYI, eslint is your friend.

Missing bracket

const ansicht = () => {
 <h1>{panel}</h1>;
};

If loading has no content, then

<Loading />

Function is missing ()

ansicht(panel)

Upvotes: 0

kiranvj
kiranvj

Reputation: 34107

Two issues here

  1. Missing bracket here <h1>{panel</h1>;

  2. panel in your const will not have the new value. You need to call the ansicht like this in your return ansicht(panel)

    const ansicht = (panel) => {
    <h1>{panel}</h1>;
    };
    

Upvotes: 1

Related Questions