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;
CodePudding user response:
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>;
}
CodePudding user response:
Your export was in the wrong place. You can't export a function into itself.
import React from 'react'
import ReactDOM from "react-dom";
export default function Welcome(props) { //ADDING EXPORT
return <h2>I am a {props.color} Car!</h2>;
}
ReactDOM.render(, document.getElementById('root'));