Reputation: 803
I am passing element to a function as a prop (named image below), e.g.
const prettyImage = (props) => {
return (
{props.image}
)}
Is there a way I can apply some styling (or generally pass some props) to props.image
inside this function?
Upvotes: 0
Views: 536
Reputation: 9856
If props.image
already is a JSX component, then this is not possible, since you want to pass a (styling) prop to a component that has already been created.
In other words: once the JSX component is created, there is no way to set its props afterwards.
I would restructure your component to achieve what you want. We have multiple choices here. Here are two of them.
Option 1: props.image is the same component but with different props
If the usage of PrettyImage
only differs from the props
passed to props.image
, then we could create the JSX component currently stored inside props.image
directly in PrettyImage
and pass the necessary props to PrettyImage
instead.
const PrettyImage = (props) => {
return (
<Image uri={props.uri} size={props.size} style={props.style} />
)
}
Making things explicit using Typescript.
type PrettyImageProps = {
uri: string,
size: number,
style?: StyleProp<ViewStyle>
}
const PrettyImage = (props: PrettyImageProps) => {
return (
<Image uri={props.uri} size={props.size} style={props.style} />
)
}
I am using Image
here just as an example. The general pattern is the same for all components. In general I would call PrettyImage
a wrapper component for Image
.
Option 2: Let props.image be the function name and use React.ceateElement
We could also use the react high level API and use React.createElement to create any JSX component on the fly in our component PrettyImage
. It is possible to pass any prop to this component.
Consider the following example.
import React from "react"
import { Text } from "react-native"
function SomeImageComponent(props) {
// or whatever. This is just a dummy
return <Text style={props.style}>Hello</Text>
}
export default function App() {
return <PrettyImage image={SomeImageComponent} />
}
export function PrettyImage(props) {
// pass some styles
return React.createElement(props.image, { style: { color: "red" } })
}
In the above code snippet it is indeed possible to pass a style object to any component since we create it at the same time.
Upvotes: 1