How to pass onPress to props.children?

Viewed 105

I'm trying to make a wrapper component in react-native that I can pass down all its props to the children it wraps around. What I really want is to pass down all function props down to all its children. It looks something like this below. I want the onPress in Wrapper to be called when the TouchableOpacity is pressed.

I tried this below but it doesn't work

const Wrapper = ({children,...props})=>{
      return <View {...props}>{children}</View>
}

const App = ()=>{
    return (
        <View style={{flex:1}}>
            <Wrapper onPress={()=>{console.log(2)}}>
                <TouchableOpacity/>
            </Wrapper>
        </View>
    )
}
2 Answers

It looks like you're looking to map the children and apply the props to each one. That might look like this:

const Wrapper = ({children,...props})=>{
  return (<>
    {React.Children.map(children, child => (
      React.cloneElement(child, {...props})
    ))}
  </>);
}

(method of mapping the children borrowed from this answer)

 const App = () => {
    return (
        <View style={{ flex: 1 }}>
            <TouchableOpacity onPress={() => {
                // do the action need here here 
            }}>


                <Wrapper  >
            </Wrapper>
        </TouchableOpacity>
            </View>
        )
    }

I would advise you to use hooks function instead

If you try to reuse functions that are related ** useAdd.js **

    export default () => {
        const addFuction(a, b) => {
            // do preprocessing here
            return a + b
        }
    
        return [addFuction]
    }

main componet

    import useAdd from "/useAdd";
    const App = () => {
        const [addFuction] = useAdd()
        return (
            <View style={{ flex: 1 }}>
                <TouchableOpacity onPress={() => {
                   addFuction(4,5)
                }}> 
                ...action component...
                      
                </TouchableOpacity>
            </View>
        )
    }

console in useAdd hook.... to see visual changes use the react useState

Related