JDLR
JDLR

Reputation: 600

Modify one component with another (HOC maybe?)

I have seen that some libraries such as "framer-motion" from react work using this syntax, for example to insert an animated H1: <motion.h1> which would translate to an h1 but with animations defined in the props of the component.

What I don't understand is how the "motion" component accesses that "h1" and then in the function it knows which component to render animated.

I need to create a component for example <lazy.div> that interprets a div with certain modifications that I am going to define.

What I need to know is how to use that syntax and not the typical

<Lazy><h1>Content<h1> </Lazy>

Would it also be possible to use this type of syntax to modify chain elements or add functions to those already modified components?

For example <lazy.fullwidth.div>

Upvotes: 1

Views: 99

Answers (1)

charlietfl
charlietfl

Reputation: 171700

When you create a function that function is an object. You can then add any properties to that object and a property itself can be another function.

So if you have a react component function you can make properties of it also be component functions.

Simple example:

const Example = () => (<div>Example Main Component</div> );

Example.h1 = () => (<h1>Example.h1 component</h1>)

const App = () => (
  <div>
    <Example />
    <Example.h1/>
  </div>  
  )

// Render it
ReactDOM.render(
  <App/>,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Upvotes: 1

Related Questions