Home > Net >  Passing Component as Props shows error: Uncaught Error: Element type is invalid: expected a string (
Passing Component as Props shows error: Uncaught Error: Element type is invalid: expected a string (

Time:09-13

I have a component named EditForm which I imported in another component called ProductList. I need to pass EditForm component from ProductList to another component ListContainer as props and render it (EditForm) inside ListContainer. The flow is given below for better understanding:

// EditForm.js

const EditForm = () => {...}
export default EditForm

// ProductList.js

import EditForm from "./EditForm"
..
<ListContainer editForm={EditForm} /> // pass the editform as props

// ListContainer.js

const ListContainer({editForm: EditForm}) => {
    ...
    <EditForm /> // use editform here
}

Here is my code below:

ProductList.js

import React from "react"
import ListContainer from "../common/ListContainer";
import EditForm from "./EditForm";

const ef = () => {
    return (<EditForm />)
}

const ProductList = () => {
    return (
        <React.Fragment>
            <ListContainer  ef={ef} />
        </React.Fragment >
    )
}

export default ProductList

ListContainer.js

import React, { useState } from "react"

const ListContainer = ({ ef: EditComponent }) => {
    return (
        <React.Fragment>
                <EditComponent />
        </React.Fragment >
    )
}

export default ListContainer

error: enter image description here

FULL CODE LINK: https://onecompiler.com/javascript/3yfvnyyf4

CodePudding user response:

React js have have Higher order component concept for dealing these type of scenarios https://reactjs.org/docs/higher-order-components.html#:~:text=A higher-order component (HOC,and returns a new component.

CodePudding user response:

Althout it's better to pass child component as props.children, but your code should works if you already uses 'export default'. Myabe you could check the props by debugging and find if there is any typo.

CodePudding user response:

If you want to pass a component down for the child to render it. The proper react way of doing it would be to pass it as props.children

For Example:

import React from "react"
import ListContainer from "../common/ListContainer";
import EditForm from "./EditForm";



const ProductList = () => {
  return (
    <React.Fragment>
        <ListContainer>
           <EditForm/>
        </ListContainer>
    </React.Fragment >
)
}

export default ProductList

You can access the children in your list container like this:

import React, { useState } from "react"

const ListContainer = ({ children }) => {
    return (
        <React.Fragment>
                <children />
        </React.Fragment >
    )
}

export default ListContainer

However if you want to pass it as a prop as you requested then the correct syntax for that is:

<React.Fragment>
   <ListContainer  ef={EditForm} />
</React.Fragment >

Hope this helps you

  • Related