Error Rendering a React Element - reactjs

I want to make a selection from a drop-down, query movies based on the selected value, map through and render them inside a react component but I got this error
A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
Here's the code:
...
constructor(props) {
super(props)
this.state = { description: '', list: [] }
}
handleList() {
axios.get('https://facebook.github.io/react-native/movies.json')
.then(resp => this.setState({...this.state, list: resp.data})) // Trás a lista atualizada e zera a descrição
console.log(this.state.list)
}
render() {
const loop = this.state.list.map((list) => {
return(
<Grid cols='2'>
<select className="form-control" key={i}>
<option value="teste" onClick={() => this.handleList()}>{list.description}</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</Grid>
)
});
}

There is a couple of issues with this code example.
You are not returning anything inside the render() function. (This is the main issue you are having, or at least that React is crying about)
You are, well at least initially, mapping over an empty array and
The callback of this map you are doing things like list.description even though there exists no list and no description inside of list during the initial render.
You are using the onClick for the options instead of onChange
The endpoint you are requesting returns an object and you try to map through it. This should error because map is not defined as a function of an object.
I have managed to fix the issues I have mentioned including the one you are currently having. To save energy, typing the long explanation and reason that went into fixing your issue, have a look at this demo. It contains the exact same code you have posted, but of course, fixed/working.

I think onclick event is not suitable to use in option. Better use it on select
` <select value={this.state.value} onChange={this.handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
`
Sicne you are rendering a list of forms to reuse the same function, I always use a closure
handleChange = (id) = () => axios
.get(`$URL/id`)
.then(r => r.data)
.then(this.setState)
render() {
return (
list.map(item => <select
key={item.id}
onChange={this.handleChange(item.id)}
>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>))}

Related

How to update div in dom with react

I have this select in a react component
<Select defaultValue="" style={{ width: 200 }} onChange={handleChange}>
<OptGroup label={correctGroup[0].Tag}>
<Option value={correctGroup[0].Text}>{correctGroup[0].Text}</Option>
<Option value={correctGroup[1].Text}>{correctGroup[1].Text}</Option>
<Option value={correctGroup[2].Text}>{correctGroup[2].Text}</Option>
</OptGroup>
<OptGroup label={wordForSelect[0].Tag}>
<Option value={wordForSelect[0].Text}>{wordForSelect[0].Text}</Option>
<Option value={wordForSelect[1].Text}>{wordForSelect[1].Text}</Option>
<Option value={wordForSelect[2].Text}>{wordForSelect[2].Text}</Option>
</OptGroup>
</Select>
Once it gets rendered it's a bunch of divs. I should also mention I'm using antd. When a user selects an option the onChange above is fired and I can see the text that was chosen.
Now based on the text I either want to make the background green or red.
So in the onchange do I use the old school document.getElementByClass to change the background. The selected item gets placed as text in an element that has a class name of "ant-select-selection-item". But since this is generated dynamically by antd I can't use useRef...
So how can I add and remove a class name from a div with the class name "ant-select-selection-item" ?
const handleChange = (value: string, defaultOptionType: any) => {
//??
};
can't you use the style prop of the option?
And you can store the style in the state. Something like this.
https://codesandbox.io/s/select-with-search-field-antd-4-22-8-forked-yt1j6e?file=/demo.js:949-954
I'm not sure if I understood the question. But one solution could be to capture the option value and then filter over all the HTML select options to find the selected option and then add a class to it.
const handleChange = (value) => {
// Get the selected option value
const selectedValue = value.target.value || null;
// Check taht there is a value
if (selectedValue) {
// Find the selected option element by the selected value
const currentOption = [...value.target.options].filter((o) => o.value === selectedValue)
// If there was a match add a class to the option
if (currentOption.length > 0) {
currentOption[0].classList.add("red");
}
}
};

Use enum in react select option

I have this enum:
const SPORTS = {
FOOTBALL: 0,
GOLF: 1,
TENNIS: 2
};
I'm trying to use those values in a react select dropdown using lodash's forIn
<select onChange={(event) => this.update(event, sport.id)}>
{_.forIn(SPORTS, (key, value) => {
{
<option value={key}>{value}</option>;
}
})}
</select>;
But am getting the error:
Invariant Violation: Objects are not valid as a React child
EDIT:
Changing to _.map works but am now seeing another issue.
Before I was manually adding all the options like which worked fine:
<option value={0}>FOOTBALL</option>;
<option value={1}>GOLF</option>;
<option value={2}>TENNIS</option>;
Now using the map I get this error:
Each child in an array or iterator should have a unique "key" prop
Now when my select boxes render they are empty but I'm not sure why.
The _.forIn() function returns the iterated object, use _.map() instead:
<select onChange={(event) => this.update(event, sport.id)}>
{_.map(SPORTS, (value, key) => (
<option value={key} key={key}>{value}</option>;
))}
</select>;

React change initial state based on another field value

How can I change the initial state value of a field based on the input value of another field?
Here's my code:
import React from "react";
export class someComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
grade: "",
tuition: changeStateHere
};
}
render() {
<div>
<form onSubmit={this.someFunction.bind(this)}>
<select name="grade" onChange={this.onChange} value={this.state.grade}>
<option value="">Class</option>
<option value="Grade One">Grade One</option>
<option value="Grade Two">Grade Two</option>
<option value="Grade Three">Grade Three</option>
<option value="Grade Four">Grade Four</option>
<option value="Grade Five">Grade Five</option>
<option value="Grade Six">Grade Six</option>
</select>
<input
type="text"
name="tuition"
placeholder="Tuition"
value={this.state.tuition}
onChange={this.onChange}
/>
</form>
</div>;
}
}
I want to set a dynamic initial state value for tuition based on input option on the grade select field.
For example, if a user selects Grade One, the tuition value should be 15000; if Grade Two, the value should be '20000'; etc.
Is there any workaround dynamically changing the initial state value?
Everything inside of the constructor is run before render. You're not going to be able to set a different initial value to the state based on something inside the render method.
Also move away from binding functions in the render method. it would be better to use a class method someFunction = () => {} and then attach it inside the JSX as onSubmit={this.someFunction}
Each time the component re-renders another instance of someFunction is bound which will eventually lead to performance issues in the browser.
You need to handle the grade selection and evaluate the event.target.value of the select element. Based on this you can use a switch to this.setState both Tuition and whether or not the input field is disabled. You should use defaultValue instead of value so that when the user picks and option it sets the input to this.state.tuition
import React from "react";
export class someComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
grade: "",
gradeSelected: false,
tuition: 0,
};
}
handleGradeSelect = event => {
let newState = Object.assign({}, this.state) // duplicate state so you can mutate this copy
switch(event.target.value){ // evaluate the value of the select option
case 'Grade One':
newState.tuition = 15000
case 'Grade Two':
newState.tuition = 20000
// You get the picture
default:
newState.tuition = 0 // needs to have a default if no option
}
newState.gradeSelected = true
this.setState(newState)
}
render() {
<div>
<form onSubmit={this.someFunction.bind(this)}>
<select name="grade" onChange={event => this.handleChange(event)}>
<option disabled>Class</option>
<option value="Grade One">Grade One</option>
<option value="Grade Two">Grade Two</option>
<option value="Grade Three">Grade Three</option>
<option value="Grade Four">Grade Four</option>
<option value="Grade Five">Grade Five</option>
<option value="Grade Six">Grade Six</option>
</select>
<input
type="text"
name="tuition"
placeholder="Tuition"
value={this.state.tuition}
onChange={this.onChange}
disabled={!this.state.gradeSelected}
/>
</form>
</div>;
}
}

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>

SCENARIO A user has a dropdown and he selects an option. I want to display that dropdown and make that option a default value which was selected by that user last time.
I am using selected attribute on option but React generates a warning asking me to use default value on select.
For e.g.
render: function() {
let option_id = [0, 1];
let options = [{name: 'a'}, {name: 'b'}];
let selectedOptionId = 0
return (
<select defaultValue={selectedOptionId}>
{option_id.map(id =>
<option key={id} value={id}>{options[id].name}</option>
)}
</select>
)
}
});
Problem is that I don't know the selectedOptionId as the selected option could be any option. How would I find the defaultValue ?
React uses value instead of selected for consistency across the form components. You can use defaultValue to set an initial value. If you're controlling the value, you should set value as well. If not, do not set value and instead handle the onChange event to react to user action.
Note that value and defaultValue should match the value of the option.
In an instance where you want to set a placeholder and not have a default value be selected, you can use this option.
<select defaultValue={'DEFAULT'} >
<option value="DEFAULT" disabled>Choose a salutation ...</option>
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Miss</option>
<option value="5">Dr</option>
</select>
Here the user is forced to pick an option!
EDIT
If this is a controlled component
In this case unfortunately you will have to use both defaultValue and value violating React a bit. This is because react by semantics does not allow setting a disabled value as active.
function TheSelectComponent(props){
let currentValue = props.curentValue || "DEFAULT";
return(
<select value={currentValue} defaultValue={'DEFAULT'} onChange={props.onChange}>
<option value="DEFAULT" disabled>Choose a salutation ...</option>
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Miss</option>
<option value="5">Dr</option>
</select>
)
}
What you could do is have the selected attribute on the <select> tag be an attribute of this.state that you set in the constructor. That way, the initial value you set (the default) and when the dropdown changes you need to change your state.
constructor(){
this.state = {
selectedId: selectedOptionId
}
}
dropdownChanged(e){
this.setState({selectedId: e.target.value});
}
render(){
return(
<select value={this.selectedId} onChange={this.dropdownChanged.bind(this)}>
{option_id.map(id =>
<option key={id} value={id}>{options[id].name}</option>
)}
</select>
);
}
Thank you all for this thread! My colleague and I just discovered that the default_value property is a Constant, not a Variable.
In other React forms I've built, the default value for a Select was preset in an associated Context. So the first time the Select was rendered, default_value was set to the correct value.
But in my latest React form (a small modal), I'm passing the values for the form as props and then using a useEffect to populate the associated Context. So the FIRST time the Select is rendered, default_value is set to null. Then when the Context is populated and the Select is supposed to be re-rendered, default_value cannot be changed and thus the initial default value is not set.
The solution was ultimately simple: Use the value property instead. But figuring out why default_value didn't work like it did with my other forms took some time.
I'm posting this to help others in the community.
Use defaultValue and onChange like this
const [myValue, setMyValue] = useState('');
<select onChange={(e) => setMyValue(e.target.value)} defaultValue={props.myprop}>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
Example
https://codesandbox.io/s/priceless-lamarr-fetpr?file=/src/App.js
With Hooks and useState
Use defaultValue to select the default value.
const statusOptions = [
{ value: 1, label: 'Publish' },
{ value: 0, label: 'Unpublish' }
];
const [statusValue, setStatusValue] = useState('');
const handleStatusChange = e => {
setStatusValue(e.value);
}
return(
<>
<Select options={statusOptions}
defaultValue={[{ value: published, label: published == 1 ? 'Publish' : 'Unpublish' }]}
onChange={handleStatusChange}
value={statusOptions.find(obj => obj.value === statusValue)} required />
</>
)
A simple solution to set the value without using selected in option,
follow these steps:
Default the value to 0 [which I am not considering it as a value to be in use] to x-column
Refer the image
4 steps
set the "IntialValue" of the x-column : 0 to the
use the same string used in your [selected] and set it here with the if condition and when found, mark the "values.x-column = 0"
Remove the "selected" and other items set [if any] in tag
4.finally set this condition
now navigate , the value in the column is defaulted to the one which is marked in step-2 / that you wanted to be set in selected
I have tried and its working for me
A small correction.. line 45 in image.. read the column as column_value_id
I tried different options to avoid console errors the following option worked with selected option without errors in console:
{const [myValue, setMyValue] = useState('');
const changeHandler = (e) => {
setMyValue(e.target.value);
};
<select id="select" value={myValue} onChange={changeHandler}>
{!myValue&& <option value="">choise from list</option>}
{elementsArr.map((el) => {
return (
<option key={el.id} value={el.name}>
{el.name}</option>
);
})
</select>}

React Bootstrap Validation use validated input in sub component

I am using react-bootstrap-validation that decorates the react-bootstrap Input tag.
The ValidatedInput requires that it is inside a Form component.
When I add my ValidatedInput to a custom sub component I get an error saying it needs to be inside a Form which it is, but I guess it is further down the tree now so can not see the Form.
Is there a way of referencing the parent Form so the ValidatedInput can see the parent.
Looking at the source of the Validation lib I can see that the ValidationInput needs to register to the Form but am not sure how to do this from the sub component.
// Parent render
render(){
<Form
className="fl-form fl-form-inline fl-form-large"
name="customer-details"
onValidSubmit={this._handleValidSubmit}
onInvalidSubmit={this._handleInvalidSubmit}
validationEvent='onChange'>
<TitleSelect handleChange={this.updateDropDown} value={this.state.form.title} />
</form>
}
// Sub class containing the ValidatedInput
export class TitleSelect extends React.Component {
static propTypes = {
handleChange: React.PropTypes.func.isRequired,
value: React.PropTypes.string.isRequired
}
render(){
return (
<ValidatedInput
name="title"
label='title'
type='select'
value={this.props.value}
onChange={this.props.handleChange}
groupClassName='form-group input-title'
wrapperClassName='fl-input-wrapper'
validate='required'
errorHelp={{
required: 'Please select a title.'
}}>
<option value="" ></option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Master">Mstr.</option>
<option value="Ms">Ms</option>
<option value="Miss">Miss</option>
<option value="Reverend">Rev.</option>
<option value="Doctor">Dr.</option>
<option value="Professor">Prof.</option>
<option value="Lord">Lord</option>
<option value="Lady">Lady</option>
<option value="Sir">Sir</option>
<option value="Master">Mstr.</option>
<option value="Miss">Miss</option>
</ValidatedInput>
)
}
};
At the moment this is impossible to do. It will be possible in a future release once we get proper parent-based contexts in react and I will migrate the component to contexts. But for now I would recommend to split your render() method to couple of smaller ones and reuse them.
Sa #Ваня Решетников said above it's impossible to do it now because of limitations of current design. A solution I went for is this.
Convert subcomponent to plain JS object
TitleSelect = {
// move prop types to parent
renderTitleSelect(){
...
}
}
Add new object as a mixin to parent and render a function
mixins: [TitleSelect],
...
render() {
<Form ...>
// parentheses are important!
{this.renderTitleSelect()}
</Form>
}

Resources