Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React isValidElement comes out as false

Here is a simple example:

const Foo = () => {
    return (
    <div>foo</div>
  );
}

class Bar extends React.Component {
    render() {
    return (
        <div>bar</div>
    )
  }
}

console.log(React.isValidElement(Foo));
console.log(React.isValidElement(Bar));

Both of these return false. Why is that?

like image 347
Kousha Avatar asked Sep 26 '17 17:09

Kousha


People also ask

How does React render false?

It works because in JavaScript, true && expression always evaluates to expression , and false && expression always evaluates to false . Therefore, if the condition is true , the element right after && will appear in the output. If it is false , React will ignore and skip it.

Why is my React prop undefined?

The "Cannot read property 'props' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.

Why is render being called twice React?

The reason why this happens is an intentional feature of the React. StrictMode . It only happens in development mode and should help to find accidental side effects in the render phase.

Is a string a valid React element?

string("Hello World")} are both of type React. element , the fundamental type for representing React elements within a React application. An element describes what you see on the screen whenever you render your application to the DOM.


1 Answers

Component != Element

Foo and Bar are components. An element is basically the result of "instantiating" (also not really, not sure what the right term is) a component. It's the combination of a constructor/function/string (for HTML components), props and children.

You get an element when you call React.createElement(Foo), which is what <Foo /> is doing under the hood.

const Foo = () => {
    return (
    <div>foo</div>
  );
}
console.log(React.isValidElement(<Foo />));
console.log(<Foo bar={42} />);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
like image 144
Felix Kling Avatar answered Sep 23 '22 18:09

Felix Kling