Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create an element in react component dynamically

Tags:

reactjs

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;
like image 967
Sumanth madey Avatar asked May 01 '18 16:05

Sumanth madey


People also ask

Is using incorrect casing use PascalCase for React components or lowercase?

Use PascalCase for React components, or lowercase for HTML elements. This happens when I separated out styled-components in a separate file and import it here. The warning will disappear if styles constants are in same file. );


2 Answers

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']); 
like image 53
Sulthan Avatar answered Sep 19 '22 17:09

Sulthan


You should user **PascalCase** Naming conventions.

For Example,

class StudentGrades extends Component{

 // Your Stuff

}
like image 43
Ravindra Miyani Avatar answered Sep 16 '22 17:09

Ravindra Miyani