Reputation: 2560
I am in parent component and i am trying to add dynamically a new component by clicking a button. I will paste only the necessary code because my files are large.
So below its the lets say the parent component:
export default class Parent extends Component {
constructor(props) {
super(props);
this.state = {
conditions: [{attribute: '', operator: '', value: ''}]
}
}
addCondition = (e) => {
this.setState((prevState) => ({
conditions: [...prevState.conditions, { attribute: '', operator: '',value: '' }],
}));
}
render() {
let {conditions} = this.state
return(
<Row>
<TextButton label='Add Child' onClick={(e) => {this.addCondition}} flat={true} />
</Row>
<Row>
<ChildElement conditions={conditions} />
</Row>
)
}
}
And this is the ChildElement that i want to render dynamically:
export class ChildElement extends Component {
constructor(props) {
super(props);
this.state = {
attribute: '',
operator: '',
action: '',
};
}
render() {
return (
this.props.conditions.map((val, idx)=> {
let attributeId = `attributeId-${idx}`,
operatorId = `operatorId-${idx}`,
valueId = `valueId-${idx}`
return (
<Row>
<Col >
<Dropdown id={attributeId} />
</Col>
<Col >
<Dropdown id={operatorId} />
</Col>
<Col>
<Dropdown id={valueId} />
</Col>
</Row>
);
})
);
}
}
When parent component is loaded i get error:
Uncaught Error: ConditionElement.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
Upvotes: 0
Views: 36
Reputation: 1525
You should enclose the value in your render
method of your child component in at least a div
. Now you return an array of components.
I don't know which version of React you are using, but you could do:
return (
<>
{ conditions.map( /* ... */ ) }
</>
);
or
return (
<div>
{ conditions.map( /* ... */ ) }
</div>
);
if <>
and </>
are not supported in your version.
Upvotes: 1
Reputation: 5766
1 - you need to actually call the function in your onClick -
onClick={(e) => {this.addCondition}}
should be either onClick={(e) => {this.addCondition()}}
or onClick={this.addCondition}
2 - You need to wrap adjacent React components in a single parent (usually <div>
or <React.Fragment>
).
Upvotes: 1
Reputation: 31024
Im going to get a wild guess here as i don't see the entire code.
You are importing the ChildElement
as if it was a default export
but actually it's a named export.
This
export class ChildElement
should be imported like that:
import {ChildElement} from './path'
And not:
import ChildElement from './path'
Upvotes: 1