最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - how to store jsx element to javascript variable - Stack Overflow

programmeradmin4浏览0评论

I want to reuse my jsx element in multiple places.

const value= <div>some text<Link href="abc">text</Link></div>

and I want to call value in multiple places.

I tried adding ' ' for the div but not getting element properly. It is returing as string. Can someone explain me the correct syntax to render jsx element to JavaScript variable?

I want to reuse my jsx element in multiple places.

const value= <div>some text<Link href="abc.com">text</Link></div>

and I want to call value in multiple places.

I tried adding ' ' for the div but not getting element properly. It is returing as string. Can someone explain me the correct syntax to render jsx element to JavaScript variable?

Share Improve this question asked Nov 8, 2019 at 17:18 devreactdevreact 1311 gold badge1 silver badge4 bronze badges 3
  • Try surrounding in brackets () – mash Commented Nov 8, 2019 at 17:19
  • 1 What error are you getting? Where you are using value ? There is too much missing information – Vencovsky Commented Nov 8, 2019 at 17:21
  • Side note: That href is invalid, unless you really have a document at ./abc.com. You need a scheme in front of it. – T.J. Crowder Commented Nov 8, 2019 at 17:22
Add a comment  | 

2 Answers 2

Reset to default 10

I want to reuse my jsx element in multiple places.

What you have works just fine:

const value= <div>some text<Link href="http://example.com">text</Link></div>;

function Example() {
    return (
        <div>
            {value}
            {value}
            {value}
        </div>
    );
)

Live Example:

const { createRoot } = ReactDOM;

function Example() {
    return (
        <div>
            {value}
            {value}
            {value}
        </div>
    );
)

createRoot(document.getElementById("root")).render(<Example />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>

It's entirely valid to create and reuse React elements that way. The JSX just creates the information React needs to render that content. The actual rendering happens when you use it, as above where I use {value} in Example.

You could create a stateless component to reuse said component:

  import React from "react"

  export const MyComponent = () => (
    <div>
      some text <Link href="abc.com">text</Link>
    </div>
  );
发布评论

评论列表(0)

  1. 暂无评论