'render props doesn't display
I am new to React and I am learning about the props. My prop doesn't display color on Events.js I got "I am a car" and red didn't display.
This is my component Welcome.js :
import React from 'react'
import ReactDOM from "react-dom";
function Welcome(props) {
return <h2>I am a {props.color} Car!</h2>;
}
ReactDOM.render(<Welcome color="red"/>, document.getElementById('root'));
export default Welcome;
my page Events.js:
import React, { useState } from "react";
import Calendar from "react-calendar";
import { render } from "react-dom";
import Form from "./Form";
import Welcome from "./Welcome"
function Events() {
const [date, setDate] = useState(new Date());
return (
<div className='app'>
<Form/>
<Welcome/>
</div>
);
}
export default Events;
Solution 1:[1]
You are not setting the prop in Events.js. This means the value of props.color is undefined when the render function is called. undefined within curly braces will be ignored by React.
You can add a guard to ensure that you see an error if the prop is not defined:
function Welcome(props) {
if (props.color == null) {
throw 'color should be defined';
}
return <h2>I am a {props.color} Car!</h2>;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
