Reputation: 197
I am using React Native and I am trying to replace some subString content with an Image-like component (react-native-auto-height-image to be precise).
The problem is, the returned parent component's props.children is just returning a string with [object Object].
Update: I realized I needed to return a map of components and not a mix of Strings and Components so I rewrote the function a bit and got closer. The problem now is that no image is being rendered:
import React from 'react';
import { Text } from 'react-native';
import AutoHeightImage from 'react-native-auto-height-image';
export default function SymbolReplacer({ text }) {
const fileLocation = '../assets/images/symbols/';
const bracketsRegex = /{.*?}/g;
const bracketContentsRegex = /{(.*?)}/;
let transforms = text.match(bracketsRegex);
let symbol = undefined;
let componentMap = undefined;
if (transforms) {
componentMap = text.split(bracketsRegex).map((text, index) => {
return <Text key={index}>{text}</Text>;
});
transforms.forEach((arr, index) => {
symbol = text.match(bracketContentsRegex)[1];
componentMap.join(<AutoHeightImage key={index} source={{ uri: `${fileLocation}${symbol}.svg` }} />);
});
}
return <Text>{componentMap || text}</Text>;
};
And the Component:
<SymbolReplacer text={"({T}: Add {U}.)"}></SymbolReplacer>
Original Code
Here is my function to do the replace based on regex inside the string (There doesn't seem to be any issue with the function logic itself, just the React portion not really returning React):
export const symbolReplacer = (text) => {
const fileLocation = '../assets/images/symbols/';
const bracketsRegex = /{(.*?)}/g;
const bracketContentsRegex = /{(.*?)}/;
let transforms = text.match(bracketsRegex);
let textWithSymbols = text;
let symbol = undefined;
if (transforms) {
transforms.reduce((arr, next, index) => {
symbol = textWithSymbols.match(bracketContentsRegex)[1];
textWithSymbols = textWithSymbols.replace(
next,
<View key={index}>
<AutoHeightImage source={{ uri: `${fileLocation}${symbol}.svg` }} />
</View>
);
return arr;
}, transforms);
}
return <Text>{textWithSymbols || text}</Text>;
};
And inside the actual Component where the function happens (Mind you, this function all works except the part that I am showing.):
const renderItem = ({ item }) => {
return (
<View>
...
<Text numberOfLines={4}>
{symbolReplacer("({T}: Add {U}.)")}
</Text>
</View>
);
};
Any idea how I can get this to return a React component with a Component inside of it and not just a string with [object Object]?
Upvotes: 1
Views: 934
Reputation: 439
You need to return a map of components for React, also I would suggest looking in to react-native-svg and using SvgUri from within it to fetch an SVG url.
Upvotes: 1