iamacup / react-native-markdown-display

React Native 100% compatible CommonMark renderer
MIT License
564 stars 166 forks source link

How to align markdown texts at center? #180

Closed shivang-vyas closed 8 months ago

shivang-vyas commented 1 year ago

how can i align markdown text at center? i have tried using ` <Markdown style={{ body: { width: '80%', alignSelf: 'center', textAlign: 'center', fontFamily: 'Nunito-Regular', fontSize: RFValue(16), color: colors.white, }, textgroup: { textAlign: 'center' }, }}

{some dynamic markdown text here} ` in style props of React Native component but it does't work accurately. specially we see this issue in ios. looks good in android though.

shivang-vyas commented 1 year ago

also tried paragraph: { textAlign: 'center' }, but its also not working in ios.

timoisalive commented 1 year ago

I was able to center align on both iOS and Android like this:

import type { FunctionComponent } from 'react';
import React, { useMemo } from 'react';
import type { TextStyle } from 'react-native';
import type { MarkdownProps } from 'react-native-markdown-display';
import MarkdownDisplay from 'react-native-markdown-display';

import { defaultTheme } from 'theme';
import { FontFamily } from 'types/fontFamily';

type Props = MarkdownProps & Pick<TextStyle, 'textAlign'>;

export const Markdown: FunctionComponent<Props> = ({ children, textAlign, ...rest }) => {
  const textAlignStyle = useMemo(() => {
    return textAlign ? { textgroup: { textAlign } } : undefined;
  }, [textAlign]);

  return (
    <MarkdownDisplay style={{ ...markdownStyle, ...textAlignStyle }} {...rest}>
      {children}
    </MarkdownDisplay>
  );
};

const markdownStyle = {
  body: {
    color: defaultTheme.colors.grey600,
    fontFamily: FontFamily.regular,
    fontSize: defaultTheme.fontSizes[4],
    lineHeight: 24,
    marginBottom: -8,
    marginTop: -8,
    padding: 0,
  },
  strong: {
    fontFamily: FontFamily.semibold,
    fontWeight: 'normal' as const,
  },
};
kyimoemin commented 1 year ago

as @timoisalive said, textAlign have to use in textgroup style property, using in text style property doesn't work.

timoisalive commented 1 year ago

To add to that, you might also need to include full width in the style in order for different blocks to center align:

textgroup: { textAlign: 'center', width: '100%' }