Skip to content
Advertisement

I defined component and used it App.js but getting undefined error

When I try to access the relevant component under app.js, I get the error “WARNING in [eslint] rcApp.js Line 2:8: ‘personAdd’ is defined but never used no-unused-vars”. When I run the project, I see tags in the form of in html, but the component does not appear on the screen. I have included the codes below. Thanks in advance. Note : Changes under .eslintrc.json didn’t work.

App.js

import React from 'react';
import personAdd from './screens/personAdd';

function App() {
    return (
      <personAdd /> 
    )
}

export default App;

personAdd.js

import React from 'react';

class personAdd extends React.Component{
    render(){
        return(
            <div id = "personAdd">
                <h1>Kullanıcı Bilgileri</h1>
                <form>
                    <label htmlFor="id">Ad</label>
                    <input id="id"/>
                    <button>Add</button>
                </form>
            </div>
        )
    }
}

export default personAdd;

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
//import personAdd from './screens/personadd';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

/*const personadd = ReactDOM.createRoot(document.getElementById('personadd'));
personadd.render(
  <React.StrictMode>
    <personAdd />
  </React.StrictMode>
);*/

   

Advertisement

Answer

You don’t need to manually create new root elements for every component you want to render.

React inserts an initial element ‘root’ into the DOM so that the app can render within that.

Try removing:

/*const personadd = ReactDOM.createRoot(document.getElementById('personadd'));
personadd.render(
  <React.StrictMode>
    <personAdd />
  </React.StrictMode>
);*/

If you want to render your personAdd component you can add it as a child of App as you’ve already done.

function App() {
    return (
      <personAdd /> 
    )
}

The other reason you’re getting these issues is because you’re not using Pascal case when naming your components (PersonAdd).

function App() {
    return (
      <PersonAdd /> 
    )
}

In addition as others have mentioned, stick to function components rather than class components.

I’d recommend having a look at the React Beta Docs which now do everything with functional components. There are helpful walkthroughs on there that should help you out.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement