19

Im not able to create a React component dynamically. I see blank page with no errors with below code.

1) Trying to create an element named "PieChart"

2) Below are the Two errors im seeing in console.

1. Warning: <PieChart /> is using incorrect casing. Use PascalCase for    
   React components, or lowercase for HTML elements.

2. Warning: The tag <PieChart/> is unrecognized in this browser. If you
   meant to    render a React component, start its name with an
   uppercase letter.

3) Im Already using Pascal case "PieChart"

import PieChart from "../component/PieChart";
class App extends Component {

  render() {
    const GraphWidget = React.createElement("PieChart");
    return (
      <div>
        {GraphWidget}

      </div>
    )
  }


}


export default App;
1
  • 3
    Don't use quotes around PieChart, i.e. const GraphWidget = React.createElement(PieChart); Commented May 1, 2018 at 16:36

3 Answers 3

24

From the createElement documentation:

Create and return a new React element of the given type. The type argument can be either a tag name string (such as 'div' or 'span'), a React component type (a class or a function), or a React fragment type.

You are trying to use a React component type therefore you cannot use a string, you need to use the class directly:

const GraphWidget = React.createElement(PieChart);

If your aim is to map strings to components, you can create simple mapping using a dictionary:

const components = {
    PieChart: PieChart
    ...
};

const GraphWidget = React.createElement(components['PieChart']); 
Sign up to request clarification or add additional context in comments.

6 Comments

Im getting "Piechart" from a Json Object as "type": "PieChart", any way i can do conversion before React.createElement(PieChart);
You can create a mapping from strings to components, I will update my answer with an example later.
I need to create a component bases on the Json response Dynamically. Do you suggest i need to create all the mappings of expected components way before? is there any way we can avoid this hard coding?
@Sumanthmadey That's exactly what I am saying. To be honest, the whole idea seems flawed. Passing a random react component through JSON is just now possible.
but how to add the key attribute to the child? createElement(FormBody, { pageConfig, key: section, } ) it doesnt apply the key to <FormBody/>
|
0

You should user **PascalCase** Naming conventions.

For Example,

class StudentGrades extends Component{

 // Your Stuff

}

Comments

-4

the component you created should start with Capital latter and using this within JSX also written with the same name

    class TodoItem extends React.Component {


      render(){

      return <TodoItem> 
     }

this could be the one of the issue

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.