I have been trying to create a dynamic from with React. So far I managed to show and hide the form without a problem. I now need to get the values from the created fields and this is causing some problems.
This is my code so far.
First my dynamic component that gets added when people click a button:
class MediaInput extends React.Component {
render() {
const linkName = `link-${this.props.index}`;
const contentName = `content-${this.props.index}`;
const linkValue = `this.props.${linkName}`;
const contentValue = `this.props.${contentName}`;
return (
<div>
<ControlLabel>Media (optional)</ControlLabel>
<input
name={ linkName }
value={ linkValue }
className="form-control"
placeholder="Add your media url"
type="text"
/>
<input
name={ contentName }
value={ contentValue }
className="form-control"
placeholder="Add your media content"
type="text"
/>
</div>
);
}
}
First in the render part I have:
const mediaFields = this.state.mediaFields.map((Element, index) => {
return <Element key={ index } index={ index } />
})
This is the part of my form where it gets rendered:
<div>
{ mediaFields }
<Button onClick={ () => this.add() }>Add media field</Button>
<Button onClick={ () => this.remove() }>Remove media field</Button>
</div>
I want to save these values in the state of the parent component:
mediaUrls: { "link-0": null, "link-1": null, "link-2": null},
mediaContents: { "content-0": null, "content-1": null, "content-2": null}
It's a bit messy but I was trying to use this example to get it to work: Example
I know that the first part, where I set linkValue and contentValue is not correct, but how should I fix it?
I also know I still need to pass the onChange method to the element but that is the next step.
UPDATE:
I think this would be a cleaner way of doing it but now I have a different problem.
I create an array where I want to store the values. I am able to read them in the child but how do I now save the changes in the parent? How can I read the index of the child in the parent so I can save it in the right place?
class MediaInput extends React.Component {
render() {
const linkName = `link${this.props.index}`;
const contentName = `content${this.props.index}`;
return (
<div>
<ControlLabel>Media (optional)</ControlLabel>
<input
onChange={this.props.handleChange}
name={ linkName }
value={ this.props.mediaUrls[this.props.index]}
className="form-control"
placeholder="Add your media url"
type="text"
/>
<input
name={ contentName }
value={ this.props.mediaContents[this.props.index]}
className="form-control"
placeholder="Add your media content"
type="text"
/>
</div>
);
}
}
My state:
mediaUrls: [ '', '', ''],
mediaContents: ['', '', ''],
How should my handleChange function look if I want to setState every time the input changes? I want to read the index and change my array based on that.
// Handle media fields
handleChange(e){
const mediaUrls = this.state.mediaUrls;
// based on the index, change the value in the array
this.setState({ ??? });
}