Git Product home page Git Product logo

react-native-draftjs-render's Introduction

React Native Draft.js Render

Build Status Coverage Status npm version license

A React Native render for Draft.js model.

Discussion and Support

Join the #react-native-render channel on DraftJS Slack team.

Documentation

Getting Started

Install React Native Draft.js Render on your React Native project, using NPM or Yarn:

yarn add react-native-draftjs-render
# or...
npm i -S react-native-draftjs-render

Using

Just import and insert your Draft.js model on getRNDraftJSBlocks:

import React from 'react';
import {
  ScrollView,
  AppRegistry,
} from 'react-native';

import getRNDraftJSBlocks from 'react-native-draftjs-render';
import contentState from 'DraftJs/contentState';

const MyApp = () => {
  const blocks = getRNDraftJSBlocks({ contentState });
  return (
    <ScrollView style={{ flex: 1 }}>{blocks}</ScrollView>
  );
};

AppRegistry.registerComponent('MyApp', () => MyApp);

See our sample folder for more details.

Adding custom styles

RNDraftJSRender comes with default styles, but you can use your own:

import React from 'react';
import {
  AppRegistry,
  ScrollView,
  StyleSheet,
} from 'react-native';

import getRNDraftJSBlocks from 'react-native-draftjs-render';
import contentState from 'DraftJs/contentState';

const styles = StyleSheet.flatten({
  paragraph: {
    color: 'pink',
    fontSize: 18,
  },
  link: {
    color: 'blue',
    fontWeight: 'bold',
  },
});

const MyApp = () => {
  const blocks = getRNDraftJSBlocks({ contentState, customStyles: styles });
  return (
    <ScrollView style={{ flex: 1 }}>{blocks}</ScrollView>
  );
};

AppRegistry.registerComponent('MyApp', () => MyApp);

See more at Custom Styles documentation.

Contributing

To develop using example react-native project:

git clone [email protected]:globocom/react-native-draftjs-render.git
cd react-native-draftjs-render/
make setup

To run tests:

make test

To watch lib changes appearing on Sample App:

make watch

To run sample app in iOS:

make ios

To run sample app in Android:

make android

react-native-draftjs-render's People

Contributors

canedo avatar darlenedms avatar davidwhitlark avatar emilianoeloi avatar eshinkawa avatar govi avatar lucassansilva avatar marcelometal avatar raphaelpor avatar rebecabordini avatar scorphus avatar vidmantas0010 avatar yoruba 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  avatar  avatar  avatar  avatar  avatar

react-native-draftjs-render's Issues

Paragraph link

When I create a paragraph that it is a link, the link style is not applied.
Thank you for your help, @raphaelpor

Custom StyleMap / decorator?

Hey guys, does this lib support megadraft customizations like a custom style map / decorator / custom entities?

Handle multiple styles in the same range

Users can define multiple styles in the same range:

[
  {
    "style":"BOLD",
    "offset":285,
    "length":14
  },
  {
    "style":"ITALIC",
    "offset":285,
    "length":14
  }
]

And the render needs to deal with it. 😈

support backgroundColor in custom styles

Hey,
I was wondering if it's possible to support the style prop backgroundColor for text blocks ?

Let's say I have those blocks:

0: {
  data: {},
  depth: 0,
  entityRanges: [],
  inlineStyleRanges: [],
  key: "6dml9",
  text: "Test",
  type: "unstyled",
},
1: {
  data: {},
  depth: 0,
  entityRanges: [{…}],
  inlineStyleRanges: [],
  key: "5dpc1",
  text: "@Coco Jumbo",
  type: "mention",
}

and this style:

mention: {
    lineHeight: 26,
    fontSize: 14,
    fontWeight: 'normal',
    backgroundColor: theme.color.blue.shade100,
  }

I'd expect the Text component corresponding to the second block with the mention style to have the background color I gave it, and looking pretty much like that:
Screenshot 2020-01-28 at 17 46 06

Do you think that would be possible ? I know the backgroundColor style prop works fine with Text components in react-native, but if you didn't handle it maybe there's a reason, I'm just curious to know if you could manage to support it or not.

Or maybe I am doing something wrong ?

Anyway, great work with this package ;)

Error: Invariant Violation: Object are not valid as react child.

Here my code:

import {StyleSheet, ScrollView, View, Button} from 'react-native';
import React, {Component} from 'react';
import {
  Container,
  Header,
  Content,
  List,
  Toast,
  ListItem,
  Text,
  Icon,
  Footer,
  Left,
  Body,
  Right,
  Separator
} from 'native-base';

import getRNDraftJSBlocks from 'react-native-draftjs-render';
import data from './content.json';


export default class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      question: "",
      answer: "",
      showAnswer: false
    }
  }

  render() {


  const params = {
    contentState: data
  };
  const blocks = getRNDraftJSBlocks(params);

  return (
    <ScrollView contentContainerStyle={styles.container}>
      {blocks}
    </ScrollView>
  );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'space-around'
  }
});

Does this project allow editing of content?

Sorry this may seem like a silly question, but does this project support editing of content? I have downloaded the project and ran the sample but it seems to be read only. Thanks for the project!

Sample

There is a problem with the sample.
After cloned, installed and run-android, the packager keeps popping error 500:
"...react-native-draftjs-render/src/getblocks doesn't exist"

Links are not tappable.

Update:

Fixed it. User error.

I took the instructions too literally and passed the blocks in as contentState rather than the whole object.

Original post

I can see links are styled with underlines, so they're detected as links, but they're not tappable.

Here's the block object:

{ 
       text: 'This is a link ',
       entityRanges: [ { length: 14, key: 0, offset: 0 } ],
       depth: 0,
       data: {},
       key: 'fos3q',
       inlineStyleRanges: [],
       type: 'unstyled' 
},

Using React Native 55

I assumed I should create an atomic handler to wrap these links in TouchableOpacity but as you can see there is no data type.

undefined is not an object 'contentstate.blocks'

I'm not sure what I did wrong.

Here is my code:

import getRNDraftJSBlocks from "react-native-draftjs-render";
import contentState from "./resourceMock.json";

export default class App extends Component {
  render() {
    const blocks = getRNDraftJSBlocks(contentState);
    return (
      <View style={styles.container}>
        <ScrollView style={{ flex: 1 }}>{blocks}</ScrollView>
      </View>
    );
  }
}

Rendering empty text blocks

It appears empty text blocks (for instance due to line breaks) are not rendered. Am I correct?

I would happily submit a PR if there is no solution available yet. Is there any solution available?

Warning : Can't call setState (or forceUpdate) on an unmounted component.

Hi all,

I've been playing around for a while with the rn-draft-render and, while everything works perfect in general, there's one small thing that I can't seem to do right while trying to embed content. I always get the warning "Can't call setState (or forceUpdate) on an unmounted component." I could live with this warning but, you know...

Here is the use case :
1- My draft contentState contains an "atomic block".
2- From this block (and from its corresponding entity) I retrieve a url.
3- I then regex the url : if it's an image I show Image, if it's a video a webview with an embed player etc.
4- Until then, everything works fine.
5- If it's not an image or a vid, I use a smart little API to retrieve the content of the webpage (title, desc, favicons, images) and to show it in a PagePreview component.
6- I fetch the classic way : my pagePreview component has a componentWillMount function and when data is retrieved it setStates the data and then the comp re-renders accordingly.
7- It works... except the warning I keep getting when the comp rerenders. What I dont understand is that my comp IS ALREADY MOUNTED. I'm not the kind of guy to call setState on an unmounted component, I would never do something like that.
8- I've tried to fetch the api from inside the atomic function but without success.

Would this be a problem with any stateful / changing state component ?

atomic:image

Please add atomic:image to getBlocks.js to support other draft editors?

   case 'atomic:image': {
          const separator = checkCounter(counters);
          if (separator) {
            const atomicView = [];
            atomicView.push(separator);
            atomicView.push(atomicHandler(item));
            return atomicView;
          }
          return atomicHandler(item);
        }

Thanks, Adri

contentState is giving error

import contentState from 'DraftJs/contentState';
After installing when im using the given sapmle code
const MyApp = () => {
const blocks = getRNDraftJSBlocks({ contentState });
return (
<ScrollView style={{ flex: 1 }}>{blocks}
);
};
its showing ERROR: unable to resolve module DraftJs/contentState

Image is not rendering. Does anybody faced this problem?

"entityMap":{"0":{"type":"IMAGE","mutability":"MUTABLE","data":{"src":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRWO_UAe27eAhTik2ggPbzKGQfuXD1oVosA_Q&usqp=CAU","height":"auto","width":"auto","alignment":"right"}}}

Typo in the readme

From:
Install React Native Draft.js Render on your Reat Native project, using NPM or Yarn:
to:
Install React Native Draft.js Render on your React Native project, using NPM or Yarn:

react native draft Objects are not valid as a React child

Hi,
I just tried to integrate "react-native-draftjs-render" into my project and just took your example, but unfortunately I get the error message:

Invariant Violation: Invariant Violation: Objects are not valid as a React child (found: object with keys {key, text, type, depth, inlineStyleRanges, entityRanges, data}). If you meant to render a collection of children, use an array instead.
    in RCTView (at View.js:44)
    in RCTScrollView (at ScrollView.js:977)
    in ScrollView (at DraftViewer.tsx:25)
    in DraftViewer (at ArticleViewDetails.tsx:42)
    in RCTView (at View.js:44)
    in RCTView (at View.js:44)
    in RCTView (at View.js:44)
    in RCTView (at View.js:44)
  ....

My code:

import * as React from 'react';
import getRNDraftJSBlocks from 'react-native-draftjs-render';
import { ScrollView, StyleSheet } from 'react-native';
import contentState from './resourceMock.json';


export interface DraftViewerProps {
    draftJSBlocks: string
}

export interface DraftViewerState {
}

export default class DraftViewer extends React.Component<DraftViewerProps, DraftViewerState> {
    constructor(props: DraftViewerProps) {
        super(props);

        this.state = {
        }
    }

    public render() {
        const blocks = getRNDraftJSBlocks({ contentState });
        return (
              <ScrollView style={{ flex: 1 }}>{blocks}</ScrollView>
        );
    }
}

My versions:
react": "16.5.2",
"react-native": "0.57.2",

Thank you for your work

problem when fetch contentState from api

it was rendered normally when i use data from local json file but it's not render when i fetch contentState from api even its a same data
here a code that i use to fetch data
const fetchdata = await fetch('https://test.com/api/story') const jsondata = await fetchdata.json(); this.setState({data:jsondata})

a log from state.data where i save fetched data to
{"blocks":[{"key":"d949g","text":"dasfsdaf","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}}],"entityMap":{}}
a log from local json
{"blocks": [{"data": [Object], "depth": 0, "entityRanges": [Array], "inlineStyleRanges": [Array], "key": "d949g", "text": "dasfsdaf", "type": "unstyled"}], "entityMap": {}}

Can't display Image

If I want to use my draft js content from react-draft-wysiwyg my react-native app wont show the image.

	"body" : {
		"blocks" : [
			{
				"key" : "8ar3c",
				"text" : "Test123 BOLD Italic ",
				"type" : "unstyled",
				"depth" : 0,
				"inlineStyleRanges" : [
					{
						"offset" : 8,
						"length" : 5,
						"style" : "BOLD"
					},
					{
						"offset" : 13,
						"length" : 7,
						"style" : "ITALIC"
					}
				],
				"entityRanges" : [ ],
				"data" : {}
			},
			{
				"key" : "oce5",
				"text" : " ",
				"type" : "atomic",
				"depth" : 0,
				"inlineStyleRanges" : [ ],
				"entityRanges" : [
					{
						"offset" : 0,
						"length" : 1,
						"key" : 0
					}
				],
				"data" : {}
			},
			{
				"key" : "152co",
				"text" : "",
				"type" : "unstyled",
				"depth" : 0,
				"inlineStyleRanges" : [ ],
				"entityRanges" : [ ],
				"data" : {}
			}
		],
		"entityMap" : {
			"0" : {
				"type" : "IMAGE",
				"mutability" : "MUTABLE",
				"data" : {
					"src" : "https://lorempixel.com/400/200/",
					"height" : "auto",
					"width" : "auto"
				}
			}
		}
	}```

Change font family based on block type + inline style

Hi there!

I am looking to have one font family for a bold header-one, and a different font family for a bold header-two. Is there any way to do this? Currently, the custom styles allows us to specify styles for block type and inline style separately, but not together.

Thanks so much!

What is DraftJs/contentState?

In the getting started it says the only library we need is this one, but then in the example it says to import DraftJs/contentState which doesnt exist?

Sorry if this is the wrong place to ask

Is support decorators ?

Hi team, package is support decorators.
Sometime, in my content have hashtag #abc , and i want to custom color it. How to ?
Thanks

Support for (un)ordered-list-item nesting

Hello, it would be nice to have support for nested list-items like the screen shot.
See the "depth" property of the "type": "ordered-list-item",
Level one = "depth": 0
Level two = "depth": 1

image

{
  "entityMap": {},
  "blocks": [
     {
      "key": "1pdm1",
      "text": "Level 1",
      "type": "ordered-list-item",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": [],
      "data": {}
    },
    {
      "key": "1sd0p",
      "text": "Level 2",
      "type": "ordered-list-item",
      "depth": 1,
      "inlineStyleRanges": [],
      "entityRanges": [],
      "data": {}
    }
  ]
}

react-navtive-drafjs-render renders the object like this.
image

Thanks, Adri

Embed content support

Hi !

First of all, great work on this ! I totally needed a project like yours and I'm happy you did it :)

Then, I'm here to make a "request". I wanted to know if you guys are planning to support the embed content (for youtube videos for example) ?

Thanks in advance :)

No line break after paragraphs?

I'm trying to render multiple paragraphs. The rendered texts show no breaks between paragraphs, which makes it very hard to read:

img_4513

As a comparison, here's the same text rendered on the web:
screenshot 2018-01-11 22 40 56

Is it possible to show line breaks? I tried adding marginBottom in paragraph's custom styles, like so:

        const customStyles = StyleSheet.flatten({
          paragraph: {
            marginBottom: 7,
            fontSize: 14,
          },
        });

It doesn't work. @raphaelpor @Canedo could you help?

Copyright holder and license

Hi,
Could you please put the copyright holder and license inside each file? This way there is no chance of someone stumbling across a piece of code without being exposed to the license.

Example for react-native-draftjs-render files:

/*
 * Copyright (c) 2017, Globo.com (https://github.com/globocom)
 *
 * License: MIT
 */

support for textInput field

I checked your sample and tried it on the emulator, but you are rendering the static data that you get from a json file.
Is there any possibility for having a textInput component and have the text entered dynamically and add the styles/images/links to the entered text?
Please help.

support for react 15.5 and higher

Please add support for react 15.5 and higher by replacing in index.js

import React, { PropTypes} from 'react';

with

import PropTypes from 'prop-types'

And use PropTypes directly in DraftJsText.js, UnorderedListItem.js, BlockQuote.js, OrderedListItem.js and TextStyled.js

import PropTypes from 'prop-types'

DraftJsText.propTypes = {
  text: PropTypes.string,
  customStyles: PropTypes.any,
  inlineStyles: PropTypes.array,
};

Thanks, Adri

Add TypeScript support

The main DraftJS project has full typescript support. Most new React Native projects are in TypeScript now. Would be nice to have support with something like yarn add @types/react-native-draftjs-render.

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.