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 |2 Answers
Reset to default 10I 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>
);
()
– mash Commented Nov 8, 2019 at 17:19value
? There is too much missing information – Vencovsky Commented Nov 8, 2019 at 17:21href
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