-2

Let’s say I have simple component in React and I want to use not only that component itself but the code of it as it is to show on screen ? How can I do that?

Here's what I m doing exactly

import Anything from ../../'anywhere';

const CustomComponent = () => {
    return (
        <div>
            <Anything />
        </div>
    )
}

export default CustomComponent;

Then in another file

import CustomComponent from './custom-component';

return (
    <div codeHighlightStr={CustomComponentString}>
        <CustomComponent />
    </div>
)

I don't know how to get CustomComponentString from the same module

HalfWebDev
  • 7,022
  • 12
  • 65
  • 103

2 Answers2

0

You can use ReactDomServer.renderToString method or some npm package by query 'jsx to string'

Alexey Baguk
  • 168
  • 1
  • 6
0

You can use <xmp> tag.

 render(){
    return (<div>
       <xmp>
       let test='SomeValue';
       document.getElementById('someElement').innetHTML = test;
       </xmp>
    </div>)
}

DEMO

brk
  • 48,835
  • 10
  • 56
  • 78
  • On the same line I was hoping, if I could not only present code inside jsx using tag but all of the module including it's import statement. For example, if I wrap my component code as string literal i.e. const Usage = `() =&gt; { import React, { useState } from 'react'; import Accordian from '../../../components/accordian/accordian'; return (<div></div>)}`, and then use eval to run that. But it doesn't runs – HalfWebDev Feb 25 '19 at 09:47
  • Is there a way to re-use all of the module code including import statements as well? – HalfWebDev Feb 25 '19 at 09:48
  • Updated my question – HalfWebDev Feb 25 '19 at 10:11