Home > Software design >  Reactjs: How to create a function with args inside a component
Reactjs: How to create a function with args inside a component

Time:12-03

In React, sometimes components have a function inside it for when an item is active or pressed like the Pressable below. How can you recreate this pattern where the pressed variable is available inside an object in the args of a function?

<Pressable onPress={ () => null }>
  { ( {pressed} ) => (
    <Text>{pressed ? "Pressed!" : "Press Me"}</Text>
  )
</Pressable>

My attempt that doesn't work

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';

const Component = ({ children }) => {
  // Not sure how active should be passed down to children
  // via a useContext maybe? Is that the only way?
  const [active, setActive] = React.useState(true);

  return <View>{children}</View>;
};

export default function App() {
  return (
    <View>
      <Component>
        {({active}) => (
          <Text>
            {active ? "Active" : "Not active"}
          </Text>
        )}
      </Component>
    </View>
  );
}

CodePudding user response:

Pass named function expression as a child to the component

import { StyleSheet, View, Text } from 'react-native'

const Component = ({ children }) => {

  const [active, setActive] = React.useState(true);

  return <View>{children(active)}</View> ;
};

export default function App() {
  const demo = (active) => (
    <Text>
      {active ? "Active" : "Not active"}
    </Text>
  );
  return (
    <View>
      <Component>
        {demo}
      </Component>
    </View>
  );
}
  • Related