user19476497
user19476497

Reputation: 557

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

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>

    }

Upvotes: 0

Views: 1301

Answers (4)

RamaProg
RamaProg

Reputation: 1387

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>
    )

}

Upvotes: 0

El Hassane Essadrati
El Hassane Essadrati

Reputation: 443

you can use something like

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

Upvotes: 1

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')

Upvotes: -1

Priyen Mehta
Priyen Mehta

Reputation: 1185

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)

Upvotes: 2

Related Questions