I have the following component structure being rendered:
<Text>
Hello <UsernameWrapper>@gaberocksall</UsernameWrapper>! Nice to meet you.
</Text>
I would like create a custom component which automatically places @username
s into a UsernameWrapper
, like this (and it should be rendered identically to the above snippet):
<AutoUsernameText>Hello @gaberocksall! Nice to meet you.</AutoUsernameText>
Or, even more generally, something along the lines of:
<MagicWrapper wrap={/@\w /gi} wrapper={UsernameWrapper}>
Hello @gaberocksall! Nice to meet you.
</MagicWrapper>
How would I go about creating the MagicWrapper
component in React Native?
CodePudding user response:
We could just create a new component where we pass the username
as a prop. In my opinion that is the way to go in react-native. Here is a quick implementation.
export const AutoUsernameText = (props) => {
return (
<Text>
Hello <UsernameWrapper>@{props.name}</UsernameWrapper>! Nice to meet you.
</Text>
)
}
Then, we can just use it as follows.
const SomeOtherScreen = () => {
return (
<AutoUsernameText name="gaberocksall" />
)
}
Notice that this solution depends on how UsernameWrapper
is actually implemented. Since I do not know that, I assume plain strings here.
If you really want to pass it as a child, e.g.
<MagicWrapper>Hello @gaberocksal! Nice to meet you.</MagicWrapper>
then AutoUsernameText
needs to parse its children and return the component you want instead. This is possible, although I do not see any good reason why one should do that. It opens many pitfalls that are not easy to avoid.
Nevertheless, we can achieve this as follows assuming that the child is a simple string using plain JS regular expressions.
export const MagicWrapper = (props) => {
// Notice that I do not guard here for potential errors ...
// props.children could be anything ...
const child = props.children
const name = child.match(/@\S ?(?=!)/g)
const content = child.split(name)
return (
<Text>
{content[0]}<UsernameWrapper>{name}</UsernameWrapper>{content[1]}
</Text>
)
}
CodePudding user response:
In order to splitting specific Regex pattern like as username, url and etc, you are able to use react-native-parsed-text package. For example it's will help you changing color of the Regex pattern (also defining custom styles) or defining onPress function to doing some things. I hope it's be useful. react-native-parsed-text github page.