score:3

Accepted answer

react functions as child components

so if i'm getting this right, you are basically asking how you could get a component which is in the following format:

<mycomponent>
  {(name) => (
    <div>{name}</div>
  )}
</mycomponent>

these are called functions as children. you do it by managing the state or a variable in a component locally and you pass that state or variable to any other component in the app by implementing the children as a function in mycomponent.

so your mycomponent component will look something as follows:

class mycomponent extends react.component { 
  render() {
    return (
      <div>
        {this.props.children('scuba steve')}
      </div>
    );
  }
}
mycomponent.proptypes = {
  children: react.proptypes.func.isrequired,
};

this allows you to reuse mycomponent anywhere with the exact same state or variables but you could render it differently.

you would find this pattern quite a lot in libraries like react-final-form for example, where the library maintains a state and the users can "consume" that state and render it in anyway they want.

you can read more about it at this link and at this link as well.

score:0

<div>
   {(value)=><span>{value}</span>}
</div>

this code is mean that you declared a function inside <div>. (not calling that function any more)

<themecontext.consumer>
    {(value) => <button style={{ background: value }}>hello context!</button>}
</themecontext.consumer>

this function will be called inside themecontext.consumer then your element will render

score:0

i see that it as more of a javascript question than a react specific; react components at the end the day will become a function; javascript support function as first-class, so a function can be passed to other function as arguments ( or returned as value ) hence the higher the components and context api. so your question can be roughly translated to this code snippet:

function theme (color) {
   /* some code maybe */
   return function nav (totalitems){
         return `i'll render a ${color} with ${totalitems} totalitems`;
   }
}

let redthemed = theme( "dark red");
let navcomp = redthemed(17);
console.log( navcomp );
console.log( redthemed(12) );

let bluethemed = theme( "light blue");
console.log( bluethemed(4) );

score:1

understand react context internals

the react context consumer children is a function instead of typical string or react element

<themecontext.consumer>
  {(value) => <button style={{ background: value }}>hello context!</button>}
</themecontext.consumer>

<div>
  hey, i'm normal jsx
</div>

the above code will be transpiled to


react.createelement(themecontext.consumer, null, function (value) {
    return react.createelement("button", {
      style: {
        background: value
      }
    }, "hello context!");
  })

react.createelement("div", null, "hey, i'm normal jsx"))

you can see that the children (props.children) is a function.


Related Query

More Query from same tag