Even though I have applied propType validation, my editor throws an error on when passing boolean value for the hasvacancy
prop. Here is what I'm seeing:
Error: 'SyntaxError: JSX value should be either an expression or a quoted JSX text'
I know I am passing a string type value for 'hasvacancy' prop but what do I need to do so I can pass a boolean or other data types via the prop.
import React from 'react'; import { render } from 'react-dom'; class VacancySign extends React.Component{ render() { console.log('------------hasvacancy------', this.props.hasvacancy); if(this.props.hasvacancy) { return( <div> <p>Vacancy</p> </div> ); } else { return( <div> <p>No-Vacancy</p> </div>); } } } VacancySign.propTypes ={ hasvacancy: React.PropTypes.bool.isRequired } render(<VacancySign hasvacancy='false'/> , document.getElementById('root'));
To pass a boolean as props to a component in React, wrap the boolean in curly braces, e.g. <Child bool={true} /> . All props you pass to a component that are not of type string have to be wrapped in curly braces.
Props are immutable, while state is mutable Although a component is not allowed to change its props, it is responsible for the props of its child components down the component tree. On the other hand, state is mutable. A stateful component changes its state every time users interact with the app.
When you use any React component you can pass it some input data that you want it to work with. These properties are called "props" and are read-only values that define the basic starting point for a component. In JSX, props look just like HTML attributes.
Use the String() function to render a boolean value in JSX in React, e.g. <h2>{String(bool1)}</h2> . By default boolean values don't render anything in React, so we have to convert the value to a string in order to render it. Copied!
You should enclose the boolean value in {}:
render(<VacancySign hasvacancy={false}/> , document.getElementById('root'));
I'm updating this answer, as my original one (omitting the value) is no longer considered best practice. Now, simply wrap your value in curly braces, as you would any other Component attribute value. So, instead of this (this still works):
render(<VacancySign hasVacancy />, document.getElementById('root'));
Do this:
render(<VacancySign hasVacancy={true} />, document.getElementById('root'));
If you're using the former syntax, make sure to update your propTypes to make hasVacancy not required; otherwise, you are free to restrict it with isRequired
:
VacancySign.propTypes ={ hasVacancy: React.PropTypes.bool.isRequired }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With