Giter Club home page Giter Club logo

react-native-simple-markdown's Introduction

react-native-simple-markdown

CircleCI npm downloads Commitizen friendly npm version

A component for rendering Markdown in React Native with native components, working with both iOS & Android. Pull requests are welcome! ๐Ÿ˜ƒ ๐ŸŽ‰

Getting started

yarn add react-native-simple-markdown

Future

This library is currently being (kinda) completely rewritten. If you've been using this lib for a short/long time or are interesting in shaping it for the future: just chime in and share your thoughts with us; or give a look at the styles section, some help is also need there!

Usage

All you need to do is import the react-native-simple-markdown and then use the <Markdown /> component.

import React from 'react'
import Markdown from 'react-native-simple-markdown'

const MyAwesomeApp = () => {
  return (
    <Markdown styles={markdownStyles}>
      #Markdown in react-native is so cool! {'\n\n'}

      You can **emphasize** what you want, or just _suggest it_ ๐Ÿ˜โ€ฆ{'\n'}

      You can even [**link your website**](https://twitter.com/Charles_Mangwa) or if you prefer: [email somebody](mailto:[email protected]){'\n'}

      Spice it up with some GIFs ๐Ÿ’ƒ:

      ![Some GIF](https://media.giphy.com/media/dkGhBWE3SyzXW/giphy.gif){'\n'}

      And even add a cool video ๐Ÿ˜Ž!{'\n'}

      [![A cool video from YT](https://img.youtube.com/vi/dQw4w9WgXcQ/0.jpg)](http://www.youtube.com/watch?v=dQw4w9WgXcQ)

      [![Another one from Vimeo](https://i.vimeocdn.com/video/399486266_640.jpg)](https://vimeo.com/57580368)
    </Markdown>   
  )
}

const markdownStyles = {
  heading1: {
    fontSize: 24,
    color: 'purple',
  },
  link: {
    color: 'pink',
  },
  mailTo: {
    color: 'orange',
  },
  text: {
    color: '#555555',
  },
}

Properties

styles

<Markdown /> will apply its style by default. However you can pass a styles prop to customize it has you wish.

Example:

<Markdown
  styles={{
    heading1: {
      fontSize: 20,
    },
    strong: {
      fontWeight: 'bold',
    }
  }}
>
  #Hello ๐Ÿ‘‹
</Markdown>

rules

Here again, <Markdown /> will apply its rules by default. However you can pass a rules prop to add your own and then customize how the Markdown elements will be displayed!

Example:

<Markdown
  rules={{
    image: {
      react: (node, output, state) => (
        <CustomImageComponent
          key={state.key}
          source={{ uri: node.target }}
        />
      ),
    },
  }}
>
  ![Alt text](/path/to/img.jpg)
</Markdown>

RNSM also allows you to remove easily unwanted styling options without having to pass in rule objects that have their react key implemented/dummied to ignore those styling options.

Example:

<Markdown
  styles={ markdownStyles }
  whitelist={['link', 'url']}
>
  { description }
</Markdown>

whitelist will only apply link and url default styles, while blacklist will do the opposite. You don't need to pass in a rules prop that contained a key for all the styles you don't want and reimplement their styling output anymore.

errorHandler

If you happened to have an error with your Markdown during the rendering, you can pass a errorHandler with a function that will let you see what's going on:

<Markdown
  errorHandler={(errors, children) => console.log(errors, children)}
>
...
</Markdown>

Styles

Given that the way React Native renders element has evolved in the latest versions (0.48+), we'll have to check manually that every single rule works as expected by:

  • rendering properly on both iOS & Android
  • being able to be styled on both platforms
  • not breaking/overriding others rules when its own is applied

When those 3 criteria are fulfilled, we can validate the Rendering column. Feel free to check any of these and send a PR to validate it on Snack!

Property Type Rendering ย Features
blockQuote <View> โŒ Also blockQuoteBar (<View>) and blockQuoteText (<Text>)
br <Text> โŒ -
del <Text> โŒ -
em <Text> โŒ -
hr <View> โŒ -
heading <Text> โŒ ย Also heading1 through heading6
image <Image> โŒ ย ou can use resizeMode in <Markdown /> styles prop to set a resizeMode
inlineCode <Text> โŒ ย -
link <Text> โŒ ย -
list <View> โŒ ย Also listItem (<View>), listItemBullet (<Text>), listItemBulletType (Unicode character), listItemNumber (<Text>) and listItemText (<Text>)
mailTo <Text> โŒ ย -
paragraph <View> โŒ ย -
plainText <Text> โŒ Used for styling text without any associated styles
strong <Text> โŒ ย -
table <View> โŒ ย -
tableHeader <View> โŒ ย -
tableHeaderCell <View> โŒ ย -
tableRow <View> โŒ ย -
tableRowCell <View> โŒ ย -
tableRowLast <View> โŒ ย Inherits from tableRow
text <Text> โŒ ย -
u <Text> โŒ ย -
url <Text> โŒ ย -
video <Image> โŒ ย Supports YouTube & Vimeo
view <View> โŒ ย This is the View container where the Markdown is rendered

Credits

This project was forked from react-native-markdown by @lwansbrough ๐Ÿ‘

react-native-simple-markdown's People

Contributors

chandlervdw avatar charlesmangwa avatar dvisco avatar leolebras avatar linonetwo avatar matusholec avatar oziks avatar romanlv avatar sospedra 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

react-native-simple-markdown's Issues

Bullets in lists not aligned properly

I get these (non properly aligned) bullets, in Android:

image

when using a list:

- Wi-Fi or Cable Fast Internet in the room\*
- PC Room rentals available\*
- 24 hour Reception
- 24 hour Security Patrols
- 24 hour Currency exchange
- Free shuttle service to Bufos beach 900m (3 times daily)
- Laundry service\*

Block level elements requiring two \n ?

Hi - Apologies if this is obvious (and/or a weird implementation of MD) but I'm getting my MD from an API which I don't control, and the block level elements (Heading, HR, etc) are only separated by one \n, whereas it appears that this implementation of it requires two \n. (I believe they're using CommonMark)
For example, I get data like:
# Heading1 #\n## Heading2 ##\n### Heading3 ###\n

But to display properly using RNSM it appears to only work if it's
# Heading1 #\n\n## Heading2 ##\n\n### Heading3 ###\n\n

I really like this library much better than the others, but this is causing some problems. I'll start looking at the code to try to figure it out, but not sure if anyone else has encountered this and if it can be solved easily.

Thanks!

The `blockQuote` is not working as expected.

Dear all,

here is my markdown:

<Markdown whitelist={['em', 'strong', 'image', 'link', 'item', 'blockQuote']}>
 The author said:{'\n'}
 > HelloWorld
</Markdown>

It seems that my markDown don't have any effect, did I do something wrong? Thanks.

[Question] Why forking `simple-markdown`?

I'm curious, I've just read the package.json file and I found out that you have forked simple-markdown, can I ask you why?

Shouldn't the library use the original project as a dependency?

I'm open to send PRs if you need a hand.

Can't combine numeric and dot lists

Example:

<Markdown>
# AA{\n\n}
- A {\n\n}
- B{\n\n}
1. aaa{\n\n}
2. bbb
<Markdown>

Renders

simulator screen shot 20 mar 2017 15 33 03

I'm happy to help with a PR if you can point me to the right direction.

Markdown image size is incorrect

When I was trying to display this image

The screen seems to display only the center of the image for some reason

Is there something that I did wrong?

Can't apply fontSize to headings

Hello!

I have simple React element with the following render method:

  render () {
    const bodyStyles = { fontSize: 12 }
    const titleStyles = { fontSize: 18 }

    return (
      <ScrollView style={styles.container}>
        <KeyboardAvoidingView behavior='position'>
          {
            this.props.items.map((item, index) => {
              return <View key={index} style={styles.item}>
                <Text style={styles.itemIndex}>{index + 1}</Text>
                <Markdown styles={{text: bodyStyles, heading: titleStyles, heading1: titleStyles}}>
                  # Heading
                  Ordinary text
                </Markdown>
              </View>
            })
          }
        </KeyboardAvoidingView>
      </ScrollView>
    )
  }

In this case, Heading has incorrect fontSize (12 instead of 18). I've tried without text style and with heading only, but no luck.

Used packages:

"react": "16.0.0-alpha.12",
"react-native": "0.47.1",
"react-native-simple-markdown": "^1.0.60-rc.3"

@CharlesMangwa , is it related to #37 ?

White listing 'hr' does not render it correctly

While below renders as expected:

        <Markdown
          styles={{ text: textStyle }}
        >
          hello{'\n'}
          ---{'\n'}
          world
        </Markdown>

putting 'hr' in whitelist does not parse --- into hr

        <Markdown
          styles={{ text: textStyle }}
          whitelist={['hr']}
        >
          hello{'\n'}
          ---{'\n'}
          world
        </Markdown>

Seems like I am missing something obvious -- any advice?

Text Color not working

I try to apply color to Paragraph. but it's not working. Other types of properties works such as backgroundColor, fontSize....

Adding react-native-simple-markdown crashes android app

Hey,

I wanted to use this library in my app, though when I try to add it to my component it causes app to crash on android. I am using React native 0.32.1 and testing the app on Nexus 5 device.

I dont have any stacktrace of what's going on and have no idea what may be wrong. What's weird is when I turn on Remote JS debug it works fine ๐Ÿ˜Ÿ

Other plugins I am using are:

    "react-native-linear-gradient": "^1.5.14",
    "react-native-router-flux": "^3.36.0",
    "react-native-simple-markdown": "^1.0.60-rc.2",
    "react-native-splash-screen": "^1.0.9"

Does Link working?

          <Markdown styles={markDownStyle}>
            #Try writing a link!
            {'\n\n'}
            [baidu](www.baidu.com/)  
              CLick it!
          </Markdown>

Seems it is not clickable?

lineHeight rendering inconsistently

Setting lineHeight on text has resulted in strange heights being applied unrelated to the value supplied. The first shot is with a lineHeight added in the markdownStyles.
screen shot 2017-06-27 at 8 57 59 am

This is without a lineHeight value in the markdownStyles for text

screen shot 2017-06-27 at 8 57 32 am

IDEA: Ability to add your own regex matching

If this was available anyone could add custom markdown on there backend and have it rendered properly on the front-end.

E.g I may want to bold & colour different keywords in a sentence

I can't do this by just using **Bolded word**, so I'd want to be able to add a custom match for ***Bolder and coloured word***

Thoughts? I'm not sure if this is possible as I haven't checked out the source ๐Ÿค”

Sub-lists doesn't render

This example of sublist doesn't work

- One
- Two
  - Three

Note the two additional spaces in the Three item. I'm open to send PR if you can point me to the right direction.

Links give errors

Whenever I use a link, I either get Cannot read property 'react' of undefined when the debugger is on, or I get undefined is not an object(evaluating 'rules[ast.type][property]') when the debugger is off. This is happening with simple links, such as the ones found on http://www.markitdown.net/markdown

Images rendering incorrect

Hi, I noticed that if I try to style the paragraph with lineHeight or changing the fontSize I get images above the text and they are incorrectly rendered.

Do you have an idea why this is happening?

Thank you ๐Ÿ˜„

screen shot 2016-10-25 at 12 19 28

Without the lineHeight property
screen shot 2016-10-25 at 12 21 55

Using `View` layout for paragraphs

As of @3b4147bd8729bb4875f0a2dbf2757e493d227cab this library is using View layout for paragraphs and all unstyled words are rendered as individual Text components. Nesting Text in View results in a lot of native controls getting rendered which is detrimental to the performance (and text rendering quality).

Is it the intention of this library to continue with that?

How to do responsive Images?

I'm trying to do this:

const markdownStyles = {

    image: {
        flex: 1,
    }

}

Why do i need to specify width and height?

Sent from my Google Nexus 5X using FastHub

Can't apply styles to links

Hi, i have a markdown, looks something like this.
And the problem is. i can't apply different colours to link and text.
For example i want to set link colour to be red, and the rest of the text should be green. What would happen is only the first word of link would be red, the rest is green.
It seems like if links and text share same style rules, text styles override all the others.

My style object:

const markdownStyles = {
  plainText : {
    color: '#424242',
  },
  link : {
    color: '#03a9f4',
  },
}

My markdown :

lorem ipsum

[Link blah blah blah][1]

  [1]: https://github.com/

Updating image height dynamically doesn't work on Android

I am rendering markdown with images and have a rule for a custom image component. It calculates the height of the image based on the screen width and updates the style in the image accordingly. While this works perfectly on iOS, it doesn't update the image height on Android. I can see in the console that the code works and updates the state, but somehow the visible image is not updated.

Updating image height without markdown works, so this is not the issue (I use my custom image component outside markdown and it works).

Here is my code:
Markdown rule for custom image component:

...
 <Markdown styles={markdownStyles}
            rules={{
              image: {
                react: (node, output, state) => (
                  <ArticleImage
                    key={state.key}
                    source={node.target}
                  />
                ),
              },
            }}
          >
            {this.state.articleContent}
          </Markdown>
...

const markdownStyles = {
  view: {
    backgroundColor: '#FFFFFF',
    width: width,
  },
  heading1: {
    fontSize: 24,
    color: '#000000',
    fontWeight: '400',
    paddingLeft: PADDING_RIGHT_AND_LEFT,
    paddingRight: PADDING_RIGHT_AND_LEFT,
    marginBottom: 15,
    marginTop: 10,
  },
  paragraph: {
    paddingLeft: PADDING_RIGHT_AND_LEFT,
    paddingRight: PADDING_RIGHT_AND_LEFT,
    fontSize: 16,
    color: '#000000',
    marginBottom: 20,
    lineHeight: 25,
  },
  blockQuote: {
    marginTop: 20,
    marginBottom: 20,
    paddingLeft: PADDING_RIGHT_AND_LEFT,
    paddingRight: PADDING_RIGHT_AND_LEFT,
    width: width-20,
  },
}

Custom image component:

import React, { Component } from 'react';
import { Image, Dimensions} from 'react-native';

const {height, width}  = Dimensions.get('window');

class ArticleImage extends Component {

  constructor(props) {
    super(props);
    this.state = {currentImageHeight: 0}
  }

  componentWillMount() {
    if (this.props.source != null){
      Image.getSize(this.props.source, (imageWidth, imageHeight) => {
        let aspectRatio = imageWidth / imageHeight
        let currentImageHeight = width / aspectRatio
        this.setState({currentImageHeight: currentImageHeight})
      }, (error) => {
        console.log("Failed to get image size:", error)
      });
    }
  }

  render () {
    return (
      <Image source={{uri: this.props.source}} style={{width: width, height: this.state.currentImageHeight}}/>
      );
  }
}

export default ArticleImage

I already tried just having rendering an image without any text (so just ![](URL)) and it still doesn't update the height. I tried removing all markdown styles. The only thing that works is if I set the image height statically.

Did anyone come across something similar or has an idea what else to try?

Line break in Simple Breakdown

I am getting standard markdown from my server as a string. I am trying to figure out if simple-markdown supports the standard line break and paragraph rules, i.e. "\n " (newline followed by 2 spaces) is a line break vs. "\n\n" is a paragraph break.

What I am observing is that "\n\n" indeed works as a paragraph break, however "\n " gives a line break followed by 2 spaces. Is this intentional or a bug. Can you please clarify.

Single line break breaks layout

A single line break \n somehow breaks the layout leading to very strange spaces. Expected behavior would be that it is just ignored.

How are list items styled?

Code:

  <Markdown
        style={{
          listItemBullet: { color: '#ed79db' },
          listItemText: { color: '#de6262' }
        }}>
        ###I am a list:{'\n\n\n'}
        - This is my first item{'\n\n'}
        - This is my second item{'\n\n'}
        - This is my third item{'\n\n'}
      </Markdown>

Result:

greenshot 2017-04-20 09 31 52

Clearly I need to fix those bullets.

Seems like the list style is not propagating correctly. Or I'm passing the wrong thing. Tried passing list:{...} as well with no luck.

Blockquotes produce error on Android

Installing from the git repo and using blockquotes on Android produces this error:

Nesting of <View> withing <Text> is not supported on Android.

Change style of markdown coponent

Hi,

I try to implement react-native-simple-markdown inside my application. Well, when I change the style, it is not applied to the text inside the markdown component.

Even if I copy paste your example, it still not working.

What can I do?

Thank you!

Code blocks should be blocks with horizontal scroll

I've noticed that code blocks render into black view in github package and into inline code blocks in npm package.

So I've played with it and have created a view which renders it without text-wrap into horizontal scroll view.

image

Just want to ask if it really needed for that lib? Because for my case it must have (Gitter mobile client).

Markdown component does not escape content correctly

My content is coming from Contentful, and apparently contains some hidden characters at the beginning and end of a string, which mess up the rendering. I am wondering what those characters could be and how to get rid of them. Here's what is happening:

  1. Including the whole body of my content:
<Markdown>
    {entry.description}
</Markdown>

Result: 
#17 April to 02 July 2017
* Test!
* Mon to Fri: 8 a.m. - 12 p.m. and 1.30 p.m. - 5 p.m.
* Sat: 9 a.m. - 1. p.m.
* Sundays closed
  1. Including a substring of the content:
<Markdown>
    {entry.description.substring(0,10)}
</Markdown>

Result (now correctly formatted): 
17 April to

The weird thing is, I have a list of items rendering the same thing and option 2 makes the first one formatted, but messes up every item after that. I have tried unescaping the text using the native unescape() function and various other ways, but nothing seems to be working...

`text` markdown style overrides other text styles.

If we configure the markdown to have a text style prop like this:

{
  text: {
    color: 'black',
  },
  heading1: {
    color: 'red',
    fontSize: 20,
    fontWeight: '500',
    marginBottom: 15,
  },
}

The text color prop in the heading1 entry will be overridden. In order to customise the text color of the heading, the text entry must be removed.

PS: I know I've opened several bugs, I'll try to send PRs for them as soon as I can.

Line Breaks

Hello! I'm trying to render Markdown from a prop

<Markdown>{this.prop.content}</Markdown>

The content is like this:

# This is my title
## Subtitle

Some text here

1. Item 1
2. Item 2

I see that you specify line breaks {'\n\n'}
What would you suggest to not have to add manually all those line breaks?

Thanks! This module is fantastic!

Centering images?

How would I go about centering the images rendered? I've tried both setting alignSelf on images style or to give it margin. None of these seem to be respected though.

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.