Giter VIP home page Giter VIP logo

jsx-to-string's Introduction

jsx-to-string

Parse your React JSX components to string

Build Status

Install

npm install jsx-to-string

Usage

import React from 'react';
import jsxToString from 'jsx-to-string';
// or var jsxToString = require('jsx-to-string');

let Basic = React.createClass({
  render() {
    return (
      <div />
    );
  }
}); //this is your react component

console.log(jsxToString(<Basic test1="test" />)); //outputs: <Basic test1="test" />

Defaults

  1. The default value for function is .... Use keyValueOverride for custom key values.

Options

  • useFunctionCode (boolean)

    Optional. Defaults to false. Whether or not to use the function actual source code instead of ...

    For example:

import React from 'react';
import jsxToString from 'jsx-to-string';
//or var jsxToString = require('jsx-to-string');

let Basic = React.createClass({
  render() {
    return (
      <div />
    );
  }
}); //this is your react component

let _onClickHandler = function () {
  //no-op
}
console.log(jsxToString(<Basic onClick={_onClickHandler} />, {
  useFunctionCode: true
})); //outputs: <Basic onClick={function _onClickHandler() { //no-op }} />
  • functionNameOnly (boolean)

    Optional. Defaults to false. Whether prop function values should contain only the name. This flag will only be used if useFunctionCode is set to true.

    For example:

import React from 'react';
import jsxToString from 'jsx-to-string';
//or var jsxToString = require('jsx-to-string');

let Basic = React.createClass({
render() {
  return (
    <div />
  );
}
}); //this is your react component

let _onClickHandler = function () {
//no-op
}
console.log(jsxToString(<Basic onClick={_onClickHandler} />, {
  functionNameOnly: true,
  useFunctionCode: true
})); //outputs: <Basic onClick={_onClickHandler} />
  • keyValueOverride (object)

    A key-value map that overrides the value of any React props with exact match with the given key. For example:

import React from 'react';
import jsxToString from 'jsx-to-string';
//or var jsxToString = require('jsx-to-string');

let Basic = React.createClass({
  render() {
    return (
      <div />
    );
  }
}); //this is your react component

let _onClickHandler = function () {
  //no-op
}
console.log(jsxToString(<Basic onClick={_onClickHandler} />, {
  keyValueOverride: {
    onClick: '_onClickHandler'
  }
})); //outputs: <Basic onClick={_onClickHandler} />
  • ignoreProps (array)

    An array of string keys that should be ignored from the JSX string. For example:

import React from 'react';
import jsxToString from 'jsx-to-string';
//or var jsxToString = require('jsx-to-string');

let Basic = React.createClass({
  render() {
    return (
      <div />
    );
  }
}); //this is your react component

console.log(jsxToString(<Basic test1="ignore" />, {
  ignoreProps: ['test1']
})); //outputs: <Basic />
  • ignoreTags (array)

    An array of string tags that should be ignored from the JSX string. For example:

import React from 'react';
import jsxToString from 'jsx-to-string';
//or var jsxToString = require('jsx-to-string');

let Basic = React.createClass({
  render() {
    return (
      <div />
    );
  }
}); //this is your react component

console.log(jsxToString(<Basic><svg /><img /><p>I am alone</p></Basic>, {
  ignoreTags: ['svg', 'img']
})); //outputs: <Basic><p>I am alone</p></Basic>
  • shortBooleanSyntax (boolean)

Optional. Defaults to false. Whether or not to show the short or long boolean syntax.

import React from 'react';
import jsxToString from 'jsx-to-string';
//or var jsxToString = require('jsx-to-string');

let Basic = React.createClass({
  render() {
    return (
      <div />
    );
  }
}); //this is your react component

console.log(jsxToString(<Basic test test2={false} test3={true}>, {
  shortBooleanSyntax: true,
})); //outputs: <Basic test test2={false} test3 />
  • displayName (string)

    A custom value to be used as the component name. For example:

import React from 'react';
import jsxToString from 'jsx-to-string';
//or var jsxToString = require('jsx-to-string');

let Basic = React.createClass({
  render() {
    return (
      <div />
    );
  }
}); //this is your react component

console.log(jsxToString(<Basic test1="ignore" />, {
  displayName: 'CustomName'
})); //outputs: <CustomName />

License

MIT

jsx-to-string's People

Contributors

adevnadia avatar alansouzati avatar amiryonatan avatar ericsoderberghp avatar georgetaveras1231 avatar gijsjan avatar lucmerceron avatar marc-rutkowski avatar peter-mouland avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsx-to-string's Issues

Nested elements not correctly parsed

I am having an issue with nested elements. This:

jsxToString(<span>one <span>two <span>three</span></span></span>)

outputs:

<span>
  <span>
    <span>
      three
    </span>
  </span>
</span>

Is this expected?

Add support for fragments

Hey, great lib! However, parsing doesn't seem to currently support <React.Fragment> or the short syntax <>.

"item is not defined" with array of objects containing function

Hi,
I try to transform an object like this
const actions = [ { component:<i className="fa fa-pencil" id="topTooltip"/>, event: () => alert('This is the first action') }, { component: <Button>Action 2</Button>, event: () => alert('This is the second action') },]

So I see that in the function stringifyObject, there is a bug in the last else if.
Indeed, item is never defined so the function is in error. Could you fixed the problem? Thanks in advance.

Can't handle null-value properties

Cannot convert undefined or null to object is thrown when a property value is null.

It appears to handle undefined, but if the property is explicitly set to null (which might be a valid input to a component), the parser can't handle it.

After updating to 1.2.0 not possible to stringify array

Hi,

I'm trying to convert a div with an array inside it but it removes the array completely from the output.
With version 1.1.0 it worked fine but after the update 1.2.0 it breaks.

Here is a test which fails with 1.2.0:

it('jsx-to-str with array input', () => {
const inputArray = ['input1', 'input2'];
const output = JsxToString(
<div>{inputArray}</div>,
);

expect(output).toContain('input1');
expect(output).toContain('input2');

});

regards,
Johan

getting error (0 , _immutable.isImmutable) is not a function

Trying to use this library to generate code blocks inline in StoryBook, however when I try to call jsxToString(component) i'm getting the error

(0 , _immutable.isImmutable) is not a function

I checked the immutable-js repo and there does seem to be a similar issue:
immutable-js/immutable-js#1165

based on a suggestion there i was able to change the line in jsx-to-string/lib/index.js [69]
from if ((0, _immutable.isImmutable)(item)) { to if ((0, _immutable.Iterable.isIterable)(item)) { and it works...

is this an issue with this library? Or is it something with immutable 4.0-rc2? The _immutable object definitely doesn't have an isImmutable function as stated. Is there something better than this semi-hacky fix? Thoughts?

Still active? + Bug

Is the repository still active? I see that the last commit was made almost four years ago, and although two of the three pull requests were approved they haven't been merged yet.

Bug...?

I'm using the package in a Next.js project and when deploying to Vercel, all Button tags get converted to seemingly random letter tags. In development this does not happen. Is this a bug or was it intentionally made like this?

code-block

Adds incorrect whitespace to output (needs "no-format" option)

If you pass this JSX string:

<p><em className="bar">foo</em>or<strong>baz</strong></p>

You get this output:

<p>
  <em className='bar'>
    foo
  </em>
  or
  <strong>
    baz
  </strong>
</p>

This will add whitespace between the em, "or" and strong, which is incorrect. If you use ReactDOMServer.renderToStaticMarkup, you get this, which is correct:

<p><em class="bar">foo</em>or<strong>baz</strong></p>

This could be resolved by a noformat or similar option, which removed indentation and newlines in the output.

JSX formatting

Currently the formatting will output props in the following fashion:

<Component name='name'
  value={1}
  isOpen={true} />

Most standards (e.g prettier) would expect something more like this:

<Component
  isOpen={true}
  value={1}
  name='name'
/>

I would suggest adding a formatting option for different formatting styles and using some defaults matching most standards.

What's your opinion ? Should I work on a PR ?

Option to put props on single line

Hi, cool library. It turned out to be exactly what I was looking for today.
Anyway, I noticed that the JSX string adds line breaks between props when the component has children. This leads to somewhat awkward looking strings.

For example,

jsxToString(<Something propA propB>Another thing</Something>, {
  shortBooleanSyntax: true
});
/*
Outputs:
<Something propA
    propB>
    Another thing
</Something>
*/

My proposal is to add an option to put props on one line. For example,

jsxToString(<Something propA propB>Another thing</Something>, {
  shortBooleanSyntax: true,
  singleLineProps: true
});
/*
Outputs:
<Something propA propB>
    Another thing
</Something>
*/

It looks like a pretty simple fix, so I may just go ahead and submit a PR.

question: would you be open to `ignoreTag` and/or `replaceTag` options?

not sure how it would work just yet, as a prop on the tag to ignore or as an option

as a prop

<Basic>
  <svg ignoreTag>
  <svg ignoreTag>
</Basic>
//outputs: <Basic ></Basic>

as an option

console.log(jsxToString(<Basic><svg /><svg /></Basic>, {
  ignoreTag: 'svg'
})); //outputs: <Basic ></Basic>

key prop is ignored

Hi, thanks for this work, I'm currently using it on a code Highlight component and works pretty well.
But one of the problems I could find is that the key prop is removed. I need that to show my code examples so the user can just copy/paste the code without getting any warnings.

Is there any way to enable this?

You can see the problem here: https://erasmo-marin.github.io/suitup-toolkit-website/

alternate boolean syntax

I'd love to see support for omitting boolean values:

eg:

<button />
<button disabled />

instead of

<button disabled={false} />
<button disabled={true} />

(respectively)

Option to not render values

Not sure how to word it exactly, sorry about that..

I would like to show the code:

<Button
  onChange={() => {
    setCount(count + 1);
  }}
>
  clicked: {count}
</Button>

But instead I am getting the rendered value of {count}:
Screen Shot 2021-03-15 at 5 11 41 PM

Is this possible?
Thanks!

Ignoring styled-jsx

Hi,

I'm working on our UI Library and I want to convect all the components to string so we can shown it as code ready to copy and paste.

We use styled-jsx and we need to convert snippets like this ⬇️ into strings.

<Button type="button" size="md" primary>Save</Button>
      <style jsx>{`
        .address{
          grid-template-columns: 66% 28%;
          display: grid;
          justify-content: space-between;
        }
`}</style>

This is the current output:

<Form> 
<Label align='right'> Name </Label> <InputText placeholder='Your Name' /> <Label align='right'> Last Name </Label> <InputText placeholder='Your Last Name' /> <Label align='right'> Address </Label> <Label align='right'> Country </Label> <Label align='right'> Do you own a car? </Label> <Label align='right'> Colors </Label> <Button type='button' primary> Save </Button> <_class styleId={2524236662} css='.address[data-jsx="2524236662"]{-ms-grid-columns: 66% 28%;grid-template-columns: 66% 28%;display: -ms-grid;display: grid;-webkit-box-pack: justify;-ms-flex-pack: justify;justify-content: space-between;} /*@ sourceURL=components/ui-library/Forms.js */ /*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi9Vc2Vycy9yaWNhcmRvcmF1Y2gvU2l0ZXMvc2NhbGVhcGkuY29tL2Zyb250ZW5kL2NvbXBvbmVudHMvdWktbGlicmFyeS9Gb3Jtcy5qcyIsImNvbXBvbmVudHMvdWktbGlicmFyeS9Gb3Jtcy5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUE0SGtCLGdDQUV1QiwwQkFDakIsQUFEaUIsK0JBQ2pCLGtCQUNpQixBQURqQixjQUNpQiwwQkFDaEMsQUFEZ0MsdUJBQ2hDLEFBR /> 
</Form>

And I want to hide:

/*@ sourceURL=components/ui-library/Forms.js */ /*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi9Vc2Vycy9yaWNhcmRvcmF1Y2gvU2l0ZXMvc2NhbGVhcGkuY29tL2Zyb250ZW5kL2NvbXBvbmVudHMvdWktbGlicmFyeS9Gb3Jtcy5qcyIsImNvbXBvbmVudHMvdWktbGlicmFyeS9Gb3Jtcy5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUE0SGtCLGdDQUV1QiwwQkFDakIsQUFEaUIsK0JBQ2pCLGtCQUNpQixBQURqQixjQUNpQiwwQkFDaEMsQUFEZ0MsdUJBQ2hDLEFBR

My code:

let codeForm = jsxToString(
      Form1,
      {
        shortBooleanSyntax: true,
        ignoreTags: ['svg', 'img', 'div', 'style jsx']
      }
    );

Thanks for this amazing lib!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.