Home > Back-end >  How can I make the text line break whenever there is a dot at the end of the text in Reactnative?
How can I make the text line break whenever there is a dot at the end of the text in Reactnative?

Time:08-19

I have text contained in state in a db called mainStory. The mainStory value is a value loaded from the backend and stored in the state.

mainStory = "hello mr musk. have you ever seen the movie looks completely diffrent from its add?. this is so weird."

I want to make a line break whenever there is a dot at the end here in rendering

What should I do? Below is my code.

    const SecondStoryContainer = styled.View`

    `;

    const CardMainTxt = styled.Text`
    `;

    const App = () => {
    const [mainStory, setMainStory] = useState('');


    <SecondStoryContainer>
    <CardMainTxt>
    {mainStory}
    </CardMainTxt>
    </SecondStoryContainer>

    }

CodePudding user response:

This is example in js, You can use like this, it works!

const myString = 'Hello, this is a string with one line. It will soon have 2 lines.'
const stringWithNewLines = myString.replaceAll('. ', '.\n');
console.log(stringWithNewLines)

CodePudding user response:

you can use something like

const newString = mainStory.replace(/\./g, '.\n');
console.log(newString)

CodePudding user response:

Ok, I think I know why the replaceAll is failing for you. It seems you set mainStory to be part of the state of the component. Therefore, you can't change it's value by doing mainStory = mainStory.replaceAll( ... )

You could do something like:

const App = () => {
    const [mainStory, setMainStory] = useState('hello mr musk. have you ever seen the movie looks completely diffrent from its add?. this is so weird.');

    const getContent = () => {
        return mainStory.replaceAll('. ', '.\n');
    }

    return (
        <SecondStoryContainer>
            <CardMainTxt>
                {getContent()}
            </CardMainTxt>
        </SecondStoryContainer>
    )

}

CodePudding user response:

Since simple linebreaks dont affect the layout, you need to use <br/> tag between senctences.

// 1) Split string into array of lines. 
// You can use this syntax to split where the ". " sequence is and not remove the ". " itself.
const lines = mainStory.split(/(?<=\. )/);

// 2) Add <br/> before each line and then remove 0th one. 
return (
  <CardMainTxt>
    {lines.flatMap((line) => [<br/>, line]).slice(1)}
  </CardMainTxt>
)

Alternatively you can wrap every line into a <div>

return (
  <CardMainTxt>
    {mainStory.split(/(?<=\. )/).map((line) => (<div>{line}</div>))
  </CardMainTxt>
)

React Native Edit: \n should actually have effect on the layout, so you can do mainStory.split('. ').join('\n')

  • Related