1

I'm a beginner in Reactjs, I was working on this small project with show me a random user using an externe Api but the problem I'm facing is it keeps showing me this warning every time when I try to render the User Component in the App.js file.

Warning:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: null.

what am I doing wrong, please? thanks.

// App.js 

import React, { useState, useEffect } from "react";
import User from "./components/User";

const url = 'https://randomuser.me/api/'

function App(){
const [User, setUser] = useState(null)
const [getRandomUser, setgetRandomUser] = useState(false)

  const fetchData = async()=>{
    const response = await fetch(url);
    const {results} = await response.json();
    const {name: { first : firstName, last: lastName },
    street : {number, name},
    login : { password},
    dob :{age},
    picture : {thumbnail: image},
          email,
        phone } = results[0]
    setUser(  {
      fullName : `${firstName} ${lastName}`,
      Adresse: `${number} ${name}`,
      email: email,
      age: age,
      password: password,
      phone: phone,
      img: image
    } )
   
  }

  useEffect(()=>{
    fetchData();
  },[getRandomUser] )

  return (
  <User/>

  )
  
}

export default App

// User.js

import React from 'react'

function User (){
 return <div>User</div>
}

export default User

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

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

2 Answers 2

1

You have a naming collision. You have both

import User from "./components/User";

and

const [User, setUser] = useState(null)

This is one reason why precise variable names and following the standard conventions are useful - something that isn't a component nor a class probably shouldn't have a variable that starts with a capital letter. Consider calling the state userData instead, and then you can pass it down to the child as a prop for the child to parse as desired, for example

const [userData, setUserData] = useState(null)
return (
  <User userData={userData} />
)
function User ({ userData }){
 return <div>User {userData ? userData.fullName : ''}</div>
}```
Sign up to request clarification or add additional context in comments.

Comments

1

You have two variables with the same name

import User from "./components/User";

and

const [User, setUser] = useState(null)

Just rename the state

const [user, setUser] = useState(null)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.