1

I am new to React and I've been told its a better way to use function components than class components and I have come to an error where I am unable to show components that I included, I don't really understand what is wrong hence the explanation might be wrong.

Please see my sandbox link for errors

https://codesandbox.io/s/sweet-andras-y1g6o?file=/src/App.js

My code as below

import React from "react";
import { Button } from "antd";

const Order = () => {
  const showAction = () => {
    <Button type="primary" size="small">
      {" "}
      {"View"}
    </Button>;
    <h1>Here</h1>;
  };
  return (
    <div>
      <h1>Hello{showAction()} Button is here</h1>
    </div>
  );
};

export default Order;

I am expecting it to show Hello {Button} Here Button is here, but instead it shows

Hello Button is here

1
  • You could be missing return inside your showAction function Commented Jan 18, 2021 at 6:04

2 Answers 2

2

Here's the working code:

import React from "react";
import { Button } from "antd";

const Order = () => {
  const showAction = () => (
    <div>
      <Button type="primary" size="small">
        {" "}
        {"View"}
      </Button>
      <h1>Here</h1>
    </div>
  );
  return (
    <div>
      <h1>Hello{showAction()} Button is here</h1>
    </div>
  );
};

export default Order;

And here's what was wrong with your code:

  1. showAction function wasn't returning anything (because you used braces instead of parentheses).
  2. All jsx elements must have a single parent element. Notice that I have added a <div> that wraps the button and the heading component. You could have also used <span> or any other component/tag of your choice.
Sign up to request clarification or add additional context in comments.

Comments

1

@Jalaj has already broken down the problem very nicely, so the only thing I would like to add is that in the case of your showAction element, you can skip adding parentheses or curly braces altogether. When doing so, JS assumes a return statement. This will work like a charm:

const showAction = () => 
    <Fragment>
      <Button type="primary" size="small">
        {" "}
        {"View"}
      </Button>
      <h1>Here</h1>
    </Fragment>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.