Home > Mobile >  how to create a wrapper that changes the props for the component in react
how to create a wrapper that changes the props for the component in react

Time:04-20

I m trying to do something with react components for the first time and need your help, I want to wrap a component inside another one dynamically and changing its props. for example, let's say I have this component:

let's suppose I want to pass the key3 from a wrapper

Note: using React-Native with TypeScript

type Props { key1: string, key2: string, key3: any }
const FirstComponent = ({ key1, key2, key3 }:Props) => {
   return <View>
    <Text>{key1} and {key2} with {key3}</Text>
<View/>
}

wrapper example

const FirstComponentWrapper = (props:Props) => {
 const value = 'something';
  return <FirstComponent {...props} key3={value} />
}

the wrapper here lets the component have the access to the key3 value. if I have a large app with a lot of components and I can't create it each time, so I m looking for a way to create the wrapper somewhere so I can call it easily.

example :

type Props = {
  component: React.ReactNode // not just function component it can be also class 
                             // component ;
  newValue: any;
}
export const Wrapper = ({ component, newValue }:Props) => {
  // this is what I missed
  // looking to return any passed component here as in the example I mentioned with new 
  // value that's added to the prop
}

any help? thanks in advance.

CodePudding user response:

You can use children in Props to render your wrapped components with your Wrapper component

type Props = {
  children: React.ReactNode 
  newValue: any;
}
export const Wrapper = ({ children, newValue, ...otherProps }: Props) => {
  return React.cloneElement(children, {...otherProps, key3: newValue})
}

Usage

<Wrapper newValue="value3">
  <FirstComponent key1="value1" key2="value2" />
</Wrapper>

Another way, you can have a higher-order component (HOC) to modify your props before your wrapped components get rendered

const withModifiedProps = (WrappedComponent: React.ReactNode) => {
   const Wrapper = ({ newValue, ...props }) => {
      return <WrappedComponent {...props} key3={newValue} />
   }
   return Wrapper
}

After that, you can wrap your component with HOC

export default withModifiedProps(FirstComponent)

Whenever you can FirstComponent, you can pass newValue to it that will automatically populate key3 as the replacement for newValue

<FirstComponent key1="value1" key2="value2" newValue="value3" />
  • Related