Search code examples
javascriptclassreactjscomponentsstateless

React Component without Function or Class?


On occasion, I have both seen and wrote some React code like this.

const text = (
  <p>
    Some text
  </p>
);

This does work, but are there any issues with this?

I know I can't use props this way, but if all I'm doing is rendering something simple like a paragraph, I don't see why I would need to make it a functional component or extend React.Component

My current reason for this is because I need to pass in a paragraph or two as placeholder text and I can't just pass in plain text.


Solution

  • This is not a react component, it is just a variable in which JSX is stored:

    const text = (
       <p>
          Some text
       </p>
    );
    

    As per DOC:

    const element = <h1>Hello, world!</h1>;
    

    This funny tag syntax is neither a string nor HTML.

    It is called JSX, and it is a syntax extension to JavaScript. We recommend using it with React to describe what the UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript.

    props will be available only in React component, either in Functional Component or a Class based Component.

    Why React is required in this if it is not a react component?

    We can store JSX in any variable and it will get transpiled by babel, and get converted into React.createElement.

    As per DOC:

    JSX just provides syntactic sugar for the React.createElement() function.

    Since JSX compiles into calls to React.createElement, the React library must also always be in scope from your JSX code.

    Example: when we write:

    var a = <div> Hello </div>
    

    Result of this will be:

    var a = React.createElement(
      "div",
      null,
      " Hello "
    );