Giter Club home page Giter Club logo

react-native-markdown-package's Introduction

npm downloads npm_downloads

React Native Markdown Package

React Native Markdown Package is a library for implementing markdown syntax in React Native.

Getting started

To install this library, you can easily run this command from your project folder.

   npm i react-native-markdown-package --save

Check this simple app for implementation example Example app

How to use

What you need to do is import the react-native-markdown-package module and then use the <Markdown/> tag.

How to use?

Here we are, take a look at this simple implementation:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, {Component} from 'react';
import {
  StyleSheet,
  ScrollView,
  View,
  Text,
  Linking
} from 'react-native';
import {
  Colors,
} from 'react-native/Libraries/NewAppScreen';
import Markdown from 'react-native-markdown-package';

const text = `
# This is Heading 1
## This is Heading 2
1. List1
2. List2
  This is a \`description\`  for List2 .\n
  * test
  * test
3. List3
4. List4.


You can also put some url as a link [like This](https://www.google.com) or write it as a plain text:
  https://www.google.com
  <[email protected]>

---

This text should be printed between horizontal rules

---

The following code is an example for codeblock:

    const a = function() {
      runSomeFunction()
    };

Below is some example to print blockquote

> Test block Quote
> Another  block Quote

this is _italic_ 
this is **strong**
Some *really* ~~basic~~ **Markdown**.


| # | Name   | Age 
|---|--------|-----|
| 1 | John   | 19  |
| 2 | Sally  | 18  |
| 3 | Stream | 20  |


this is an example for adding picture:

![Screen Shot 2019-10-05 at 3 19 33 AM](https://user-images.githubusercontent.com/26213148/66237659-d11f4280-e71f-11e9-91e3-7a3f08659d89.png)


`;

export default class App extends Component<{}> {
  render() {
    return (
      <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={styles.scrollView}>
      <View style={styles.container}>
          <Text style={styles.welcome}>
            Welcome to React Native!
          </Text>
          <Markdown 
            styles={markdownStyle.collectiveMd} 
            onLink={(url) => Linking.openURL(url)}
          >
            { text } 
          </Markdown>
          <Markdown 
            styles={markdownStyle.singleLineMd}
          >
            this is a test single line md
          </Markdown>
      </View>
    </ScrollView>
    );
  }
}
const singleStyle = {
  text: {
    color: 'blue',
    textAlign: "right"
  },
  view: {
    alignSelf: 'stretch',
  }
};

const markdownStyle = {
  singleLineMd: {
    text: {
      color: 'blue',
      textAlign: "right"
    },
    view: {
      alignSelf: 'stretch',
    }
  },
  collectiveMd: {
    heading1: {
      color: 'red'
    },
    heading2: {
      color: 'green',
      textAlign: "right"
    },
    strong: {
      color: 'blue'
    },
    em: {
      color: 'cyan'
    },
    text: {
      color: 'black',
    },
    blockQuoteText: {
      color: 'grey'
    },
    blockQuoteSection: {
      flexDirection: 'row',
    },
    blockQuoteSectionBar: {
      width: 3,
      height: null,
      backgroundColor: '#DDDDDD',
      marginRight: 15,
    },
    codeBlock: {
      fontFamily: 'Courier',
      fontWeight: '500',
      backgroundColor: '#DDDDDD',
    },
    tableHeader: {
      backgroundColor: 'grey',
    },
  }
});

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
    margin: 10,
    padding:20
  },
  scrollView: {
    backgroundColor: Colors.lighter,
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  }
});

Properties

styles

Default style properties will be applied to the markdown. You could replace it with your preference by adding styles property like the example above.

onLink

This prop will accept a function. This is a callback function for any link inside markdown syntax, so you could costumize the handler for onClick event from the link.

onLinkCallback should be a function that returns a promise.


const onLinkCallback = (url) => {
  console.log('test test test');

  const isErrorResult = false;

  return new Promise((resolve, reject) => {
    isErrorResult ? reject() : resolve();
  });
};

...

<Markdown
  styles={markdownStyle.collectiveMd}
  onLink={onLinkCallback}>
  {text}
</Markdown>

...


NOTE : Email link (mailto) could be tested on real device only, it won't be able to test on Simulator as discuss in this StackOverflow

Thanks To

thanks to all contributors who help me to make this libary better

This project was actually forked from lwansbrough , with some enhancements below :

  1. Styling method.

    Now you can easily add styling on each syntax, e.g. add different color either in strong, header, or another md syntax. All default styles in this package is also already moved to new file styles.js.

  2. Refactoring some codes to adopt ES6 style.

    Refactor index.js using ES6. :)

  3. Support Sublist.

    In the previous library, you couldn't add sublist. It was not supported. But now, this feature already added here. Please follow the instruction above...

  4. Latest release:

    • add Proptypes Support, (1.0.1)

    • Fix deprecated View.proptypes and update Readme (1.0.3)

    • Upgrade dependency, lodash, avoid vulnerabilities (1.1.0)

    • Fix performance issue, import only necessarry function from lodash (1.1.1)

    • Finalize Blockquote feature (1.2.0)

    • Update Docs (1.2.1)

    • Allow user to include plain text from variable using back tick (1.3.3)

    • New feature, codeblock (1.4.0)

    • New feature, on link handler (1.4.3)

    • Bug fix, Strike through issue (1.4.4)

    • Default Style for outer View, remove deprecated ComponentWillMount (1.5.0)

    • Allow user to replace default rules, update default font family for codeBlock on android (v1.6.0)

    • Update to use latest simple-markdown (v1.7.0)

    • Update to use latest simple-markdown (v1.8.0)

    • Remove deprecated prop-types from list of dependencies (v1.8.2)

react-native-markdown-package's People

Contributors

andangr avatar andangrd avatar deadcoder0904 avatar dependabot[bot] avatar ntcong91 avatar vangalilea 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-markdown-package's Issues

Block Quote styling

Hi, Andang, first of all thank you for creating this open source repo for everyone to use ✨ Really appreciate the work to create and maintain this repo.

I have a question related to block quote styling here. Is it intentional to add the blockQuoteText twice? I notice we also add the styling to the text component right? Why do we need to add the styling in our View component?

        return React.createElement(View, {
          key: state.key,
          style: [styles.blockQuoteSection, styles.blockQuoteText],
        }, [img, blockQuote]);

I ask because I want to add spacings to blockQuoteText styling, but ended up having twice the spacings that I want. (in the Text and in the View components).

Thank you, have a good day!

Bug with first list items wrapped in unneeded View

Using a custom font, I discovered that the list items are not rendered the same way.

The following example markdown is given:

* Test 1 ß
* Test 2 ß
* Test 3 ß

The first list item text is wrapped in another View which makes it ignore setting a custom font:
Screen Shot 2019-05-01 at 12 36 18

Clearly visible in RN Debugger:
Screen Shot 2019-05-01 at 12 55 45

The text of the first list item is wrapped in another View which receives the style, the others list items are just text nodes.

ViewPropTypes no longer supported by react-native-web

This line:

import {View, ViewPropTypes} from 'react-native';

causes problems with relatively recent versions of react-native-web. Basically, support for those has been removed in December 2019 (necolas/react-native-web@1ad1693).

According to the author, he removed it because react-native will stop supporting it, and he won't put it back (necolas/react-native-web#1543). Not having proptypes isn't really an issue most of the time, so...

Please replace with PropTypes.shape(), or remove completely.

Crash when using >

This crashes:
'* Test \n\n>detta är ett test';

This works:
'* Test \n\n >detta är ett test';

For some reason the space before '>' is need or else I get a crash.
Im using 1.0.3.

'xxx text: ', '* Test \n\n>detta är ett test' 01-24 16:14:06.769 3747-5461/com.engagingcare E/ReactNativeJS: ReferenceError: Can't find variable: get This error is located at: in Markdown (at ArticleBodyText.js:19)

linkTo not accepting a function

Readme says 'you could customise the handler for onClick event from the link.'

But cannot find how to do this as only appears to accept the structure:
onLink={(url) => Linking.openURL(url)}

Replacing Linking.openUrl(url) with anything else like the below throws an error:

onLink={(url) => function () {
    console.log('test');
}}>

onLink={(url) => fn(url)}

ERROR:

TypeError: undefined is not an onbject (evaluating 'opts onLink(target).catch')

The end result ideally would be to utilise a link within the markdown to naviagte to another screen within a ReactNative app.

[Question] Custom styling with RN Markdown package

Hello,
I'm currently using this package to parse text with Markdown syntax, however I cannot use custom style (color, font etc.) on Markdown elements.

Is it only me, or this is an unavailable feature ? How could I work around that without dropping this really handy package ?

Thanks in advance for your answer !

SVG rendering support

Hey there! I'm using this package for a small project and I realized you render images with the react-native Image component which does not support SVG files. I made some small changes to support SVG uri's with react-native-svg. I tried opening a PR but couldn't. Is this something you would like to add to the package? I would need write permissions then.

Let me know what you think! Here's the proposed diff.

diff --git a/rules.js b/rules.js
index 789b67f..faa5ba2 100644
--- a/rules.js
+++ b/rules.js
@@ -1,5 +1,5 @@
 import React from 'react';
-
+import { SvgUri } from 'react-native-svg';
 import {
   Image,
   Text,
@@ -141,12 +141,20 @@ module.exports = function (styles, opts = {}) {
       react: function (node, output, {...state}) {
         var imageParam = opts.imageParam ? opts.imageParam : '';
         var target = node.target + imageParam;
-        var image = React.createElement(Image, {
-          key: state.key,
-          // resizeMode: 'contain',
-          source: {uri: target},
-          style: styles.image,
-        });
+        var image
+        if (target.match(/.*\.svg(\?.*)?$/)) {
+          image = React.createElement(SvgUri, {
+            key: state.key,
+            uri: target,
+            style: styles.image,
+          });
+        } else{
+          image = React.createElement(Image, {
+            key: state.key,
+            source: {uri: target},
+            style: styles.image,
+          });
+        }
         if (enableLightBox) {
           return React.createElement(Lightbox, {
             activeProps: styles.imageBox,

The only remaining thing other than this would be adding the dependency to the package.json and the lock file.

Being able to style images in markdown

Everything has its own styling like so...

collectiveMd: {
heading1: {
color: 'red'
},
heading2: {
color: 'green',
textAlign: "right"
},
strong: {
color: 'blue'
},
em: {
color: 'cyan'
},

but images don't have styling. Or is there?

if not can you please consider adding it? Thanks 

Not detecting new lines

Love the package first of all!

We're having the issue that new (empty) lines are not being detected. I've been looking through the package, but cant get it to detect it.

So ideally we were able to insert as many break lines to manage spacing.

EXAMPLE

3 empty lines below this line


1 empty line below me 

Markdown is often used to format readme files

Is there any way to do this?

Deprecated View.propTypes

I think this is deprecated in RN 0.50.4:
view: View.propTypes.style,

It does not give any warnings for me, but on iOS it crashes in release.

Unable to make text italic.

I am using the latest ver 1.8.2. When i put text between single underscore or asterisk
itali or italic
It don't make it italic. For double underscore it make it strong. Please help

Typescript support

Hi, i'm just curious since this wasn't stated in the docs, is typescript support available with this package?

Documentation thus overview of all the classes missing

As it's not the tags (eg. not p but paragraph) rendered to the elements, I miss a complete list of all the classes that become accessible in the markdown run.

The example covers only a part of it.

My best source of information is the style.js file. But even there some guessing is needed. (eg. there is list, sublist, listItem and listRow and I have a hard time translating this into stylable elements)

Thanks for your consideration!

Remove default use of font Courier

Hi,

great work on that package. However, I think something can be improved: this package use Courier as a default font for code / inline code blocks. However, Courier is not available in Android and it throws an error.

I think the styles should check if the platform is iOs before using Courier (or even just simply use monospace, not Courier);

import { Dimensions, StyleSheet, Platform } from 'react-native';
const monospaceFont = Platform.OS === 'ios' ? 'Courier' : 'monospace';

Use of blockquote or applying blockquote style throws exception in React Native debugger.

When using the plugin on android with react native debugger. There seems to be a high priority warning that shows saying "Invalid props.style key color supplied to View.
Bad object: {
"flexDirection": "row",
"color": "grey"
}"

if you either have a blockquote in your text with no style override or if you have a block quote style override or both.

Here is some sample code to replicate the error.

Sample #1

const text = `
# This is Heading 1
## This is Heading 2
1. List1
2. List2
  This is a \`description\`  for List2 .\n
  * test
  * test
3. List3
4. List4.


You can also put some url as a link [like This](https://www.google.com) or write it as a plain text:
  https://www.google.com
  <[email protected]>

---

This text should be printed between horizontal rules

---

The following code is an example for codeblock:

    const a = function() {
      runSomeFunction()
    };

Below is some example to print blockquote



this is _italic_ 
this is **strong**
Some *really* basic **Markdown**.


| # | Name   | Age 
|---|--------|-----|
| 1 | John   | 19  |
| 2 | Sally  | 18  |
| 3 | Stream | 20  |
`;


const Test = () => (
  <View style={styles.container}>
    <Text style={styles.welcome}>
            Welcome to React Native!
    </Text>
    <Markdown
      styles={styles.markdown}
    >
      { text }
    </Markdown>

  </View>
);


const styles = {
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
    margin: 10,
    padding:20
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  markdown: {
    heading1: {
      color: 'red'
    },
    heading2: {
      color: 'green'
    },
    strong: {
      color: 'blue'
    },
    em: {
      color: 'cyan'
    },
    text: {
      color: 'black',
    },
    /*blockQuoteText: {
      color: 'grey'
    },
    blockQuoteSection: {
      flexDirection: 'row',
    },*/
    blockQuoteSectionBar: {
      width: 3,
      height: null,
      backgroundColor: '#DDDDDD',
      marginRight: 15,
    },
    codeBlock: {
      fontFamily: 'Courier',
      fontWeight: '500',
      backgroundColor: '#DDDDDD',
    },
    tableHeader: {
      backgroundColor: 'grey',
    },
  }
};

Notice in this sample the block quotes are taken out of the test text. If you uncomment "blockQuoteText" and "blockQuoteSection" you'll get those high priority warnings about invalid style props and bad object.

Sample #2

const text = `
# This is Heading 1
## This is Heading 2
1. List1
2. List2
  This is a \`description\`  for List2 .\n
  * test
  * test
3. List3
4. List4.


You can also put some url as a link [like This](https://www.google.com) or write it as a plain text:
  https://www.google.com
  <[email protected]>

---

This text should be printed between horizontal rules

---

The following code is an example for codeblock:

    const a = function() {
      runSomeFunction()
    };

Below is some example to print blockquote

> Test block Quote
> Another  block Quote

this is _italic_ 
this is **strong**
Some *really* basic **Markdown**.


| # | Name   | Age 
|---|--------|-----|
| 1 | John   | 19  |
| 2 | Sally  | 18  |
| 3 | Stream | 20  |
`;


const Test = () => (
  <View>
    <Text >
            Welcome to React Native!
    </Text>
    <Markdown
      
    >
      { text }
    </Markdown>

  </View>
);

In sample number 2. Notice all styles are removed. The error will still throw, but will go away if you take the block quotes out of the text constant.

Warning with rendered component

The tree rendered contains children with the same key 0, which leads to a warning in the debugger.

ExceptionsManager.js:82 Warning: Encountered two children with the same key, `0`. 
Keys should be unique so that components maintain their identity across updates. 
Non-unique keys may cause children to be duplicated and/or omitted  the behavior 
is unsupported and could change in a future version.
    in RCTView (at View.js:45)
    in View (created by Markdown)
    in RCTView (at View.js:45)
    in View (at react-native-markdown-package/index.js:53)
    in Markdown (at browsererror.js:77)
    in RCTView (at View.js:45)
    in View (at browsererror.js:72)
    in RCTView (at View.js:45)
    in View (at browsererror.js:71)
    in RCTScrollContentView (at ScrollView.js:959)
    in RCTScrollView (at ScrollView.js:1098)
    in ScrollView (at GestureHandler.js:395)
    in NativeViewGestureHandler (at GestureHandler.js:394)
    in ComponentWrapper (at createNavigationAwareScrollable.js:53)
    in withNavigationScrolling(ComponentWrapper) (created by Context.Consumer)
    in withNavigation(withNavigationScrolling(ComponentWrapper)) (at createNavigationAwareScrollable.js:107)
    in NavigationAwareScrollable(ComponentWrapper) (at browsererror.js:70)
    in RCTView (at View.js:45)
    in View (at browsererror.js:69)
    in RCTView (at View.js:45)
    in View (at WebView.ios.js:291)
    in WebView (at BrowserScreen.js:217)
    in BrowserScreen (created by SceneView)
    in SceneView (at StackViewLayout.js:797)
    in RCTView (at View.js:45)
    in View (at createAnimatedComponent.js:151)
    in AnimatedComponent (at StackViewCard.js:69)
    in RCTView (at View.js:45)
    in View (at createAnimatedComponent.js:151)
    in AnimatedComponent (at screens.native.js:59)
    in Screen (at StackViewCard.js:57)
    in Card (at createPointerEventsContainer.js:27)
    in Container (at StackViewLayout.js:862)
    in RCTView (at View.js:45)
    in View (at screens.native.js:83)
    in ScreenContainer (at StackViewLayout.js:313)
    in RCTView (at View.js:45)
    in View (at createAnimatedComponent.js:151)
    in AnimatedComponent (at StackViewLayout.js:309)
    in PanGestureHandler (at StackViewLayout.js:302)
    in StackViewLayout (at withOrientation.js:30)
    in withOrientation (at StackView.js:79)
    in RCTView (at View.js:45)
    in View (at Transitioner.js:214)
    in Transitioner (at StackView.js:22)
    in StackView (created by Navigator)
    in Navigator (at createKeyboardAwareNavigator.js:12)
    in KeyboardAwareNavigator (created by SceneView)
    in SceneView (at createTabNavigator.js:39)
    in RCTView (at View.js:45)
    in View (at ResourceSavingScene.js:37)
    in RCTView (at View.js:45)
    in View (at ResourceSavingScene.js:26)
    in ResourceSavingScene (at createBottomTabNavigator.js:121)
    in RCTView (at View.js:45)
    in View (at screens.native.js:83)
    in ScreenContainer (at createBottomTabNavigator.js:111)
    in RCTView (at View.js:45)
    in View (at createBottomTabNavigator.js:110)
    in TabNavigationView (at createTabNavigator.js:197)
    in NavigationView (created by Navigator)
    in Navigator (at createAppContainer.js:387)
    in NavigationContainer (at App.js:16)
    in App (at renderApplication.js:35)
    in RCTView (at View.js:45)
    in View (at AppContainer.js:98)
    in RCTView (at View.js:45)
    in View (at AppContainer.js:115)
    in AppContainer (at renderApplication.js:34)

ViewPropTypes error with new react-native version

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch [email protected] for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/react-native-markdown-package/index.js b/node_modules/react-native-markdown-package/index.js
index 3d9a15b..7264267 100644
--- a/node_modules/react-native-markdown-package/index.js
+++ b/node_modules/react-native-markdown-package/index.js
@@ -1,9 +1,10 @@
 import React, {Component} from 'react';
-import {View, ViewPropTypes} from 'react-native';
+import {View} from 'react-native';
 import {merge, isEqual, isArray} from 'lodash';
 import PropTypes from 'prop-types';
 import SimpleMarkdown from 'simple-markdown';
 import styles from './styles';
+import { ViewPropTypes } from 'deprecated-react-native-prop-types';
 
 class Markdown extends Component {
   constructor(props) {

This issue body was partially generated by patch-package.

markdown parses list

I have a text like this
`

  • bullet \r- List
  1. Numbered\r2. List\r3. List
    ` ;
    after parsed and it shows
    • bullet
    • List
    • Numbered
    • List
    • List
    but I suppose it should be
    • bullet
    • List
  2. Numbered
  3. List
  4. List

Unordered list as first level

How can we show unordered lists as first level (not a sublist). Been trying some things (*, -, +) and none worked out.

Blockquote overflows margin

The blockquote text overflows the margin. Given a simple example where the outer container has a margin or padding:

<View style={styles.markdownContainer}>
  <Markdown styles={markdownStyles}>
    ... blockquote text here ...
  </Markdown>
</View>
const styles = StyleSheet.create({
    markdownContainer: {
        flex: 1,
        marginHorizontal: 20,
    },
});

Result
Screen Shot 2019-04-18 at 12 39 01

Not related to my custom style, also observable with the default style.

ViewPropTypes will be removed from React Native. Migrate to ViewPropTypes exported from 'deprecated-react-native-prop-types'

Hello ! Since the release of React native 0.68 this warning is displayed when I'm opening my app using your package : ViewPropTypes will be removed from React Native. Migrate to ViewPropTypes exported from 'deprecated-react-native-prop-types'.

Is it possible for you to fix it ? I think you should replace import {ViewPropTypes} from 'react-native' by import {ViewPropTypes} from 'deprecated-react-native-prop-types' in index.js (line 2)

Have a nice day :)

How to use asset images

Probably I'm missing it, but is there a way to use a callback for using images from the assets? I only stumbled about your enableLightbox..

Url not clickable

Its not possible to click on urls.

react-native: 0.50.4
react-native-markdown-package: 1.0.1

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.