Reputation: 344
I have a prop classifiers array in my react component which changes when a file is uploaded via a form. I have to populate the classifiers field in my form based on the value of the classifier array. I am calling this.render() when the classifiers array is changed, but the list is not being populated.
Constructor:
constructor() {
super();
this.classifiers = [];
}
Render method:
render() {
if(this.classifiers.length!==0){
return(
<form>
</form>
)
}
else{
return(
<form>
</form>
)
}
}
Assume that the form component is written correctly. When I put some console logs into the if and the else of render, they work fine but the component is not rerendered with the new classifiers.
Upvotes: 0
Views: 2648
Reputation: 1119
I have a prop classifiers array in my react component which changes when a file is uploaded via a form.
classifier is not related to prop it is a class variable
I have to populate the classifiers field in my form based on the value of the classifier array.
When in a component you are having something that changes or varies from time to time please use state for that
this.state = {
classifier: []
}
I am calling this.render()
render()
it is meant to be called by react not explicitly by user. Do not interrupt the flow.
I suppose you can change classifier very well. If not you can change it as
const updateClassifier = (items= []) => {
this.setState((prevState) => {
return {
classifier: [...prevState.classifier, ...items]
}
})
}
For rendering the form
const renderMyForm = () => {
if(this.state.classifier.length !== 0){
return (<form></form>);
} else {
return (<form></form>);
}
}
render() {
{ renderMyForm ()}
}
Upvotes: 1
Reputation: 2878
The component is not updated by props but state... change state isteed of props...
this.setState({ whateverHere })
Upvotes: 1