How to create View component which width match Text inside it #1201
tomaszzmudzinski
started this conversation in
General
Replies: 2 comments
-
One possible way to do is use canvas.measureText method to calculate the width and use the width as inline CSS to style the View container. For example, here is sample code below: const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let text = ctx.measureText('Hello world');
console.log(text.width); // 56;
<View style={{width: textwidth}}>
<Text>Hello world</Text>
</View> For your reference, here is the link to the measureText doc: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/measureText |
Beta Was this translation helpful? Give feedback.
0 replies
-
Here's how I did it const pillStyles = StyleSheet.create({
pillContainer: {
flexDirection: "row",
alignItems: "center",
},
pill: {
borderRadius: 12,
paddingVertical: 4,
paddingHorizontal: 8,
alignSelf: "flex-start",
border: "1px solid black",
},
pillText: {
color: "black",
fontSize: 8,
},
});
const Pill = ({
text,
backgroundColor = "#ffb3d2",
}: {
text: string;
backgroundColor?: string;
}) => (
<View style={pillStyles.pillContainer}>
<View style={{ ...pillStyles.pill, backgroundColor }}>
<Text style={pillStyles.pillText}>{text}</Text>
</View>
</View>
); |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
I am trying to use View Component and Text Component to create something which looks like a button. The view component should always have the width of text inside it + padding given in styles. Don't know why, but the view component always has the width of the whole page.
It works differently in raw HTML. Example below:
Could anyone tell me how to do it? I can't set width manually because the text is dynamic so its width can change.
Beta Was this translation helpful? Give feedback.
All reactions