I'm learning react
and made some components with inputs. I have several events where i use event.target.value
, But the problem is that they overwrite each other.
How can I set a specific name for each event.target.value
, something like event.target.myname.value
To understand in more detail please see here Code in stackblitz
Below is the code that I need to change and make events here with some kind of identifier so that they are not overwritten with other values.
class Range extends React.Component {
render() {
return (
<div>
<label for="f-size">Font size(from 1 to 50): {event.target.value}px</label>
<input
type="range"
id="f-size"
defaultValue="14"
name="fsize"
min="1"
max="50"
onChange={(event)=>this.props.fzCallback(event.target.value)}
/>
<p style={{ fontSize: `${event.target.value}px`}}>
Test text for font size range input.
</p>
</div>
);
}
}
export default Range;
App.js
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
fz: '',
};
}
handleFz = (fzData) => {
this.setState((prev) => ({ ...prev, fz: fzData }));
};
render() {
return (
<div>
<div>
<Range fzCallback={this.handleFz} />
</div>
</div>
);
}
}
export default App;
I would be very grateful if someone could help me solve this.
CodePudding user response:
The problem is that you are using the Window event
property which returns the current Event the handled by the site. (More on that here: https://developer.mozilla.org/en-US/docs/Web/API/Window/event)
The way to fix your problem is passing props to your child components.
So for example the Range
component would look like that:
class Range extends React.Component {
render() {
return (
<div>
<label for="f-size">Font size(from 1 to 50): {this.props.value}px</label>
<input
type="range"
id="f-size"
defaultValue="14"
name="fsize"
min="1"
max="50"
onChange={(event)=>this.props.fzCallback(event.target.value)}
/>
<p style={{ fontSize: `${this.props.value}px`}}>
Test text for font size range input.
</p>
</div>
);
}
}
And your App
component:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
inp: '',
bg: '',
fc: '',
fz: '',
};
}
handleColor = (colorData) => {
this.setState((prev) => ({ ...prev, fc: colorData }));
};
handleBg = (bgData) => {
this.setState((prev) => ({ ...prev, bg: bgData }));
};
handleFz = (fzData) => {
this.setState((prev) => ({ ...prev, fz: fzData }));
};
handleCallback = (childData) => {
this.setState({ inp: childData });
};
handleReset = () => {
this.setState({ inp: '' });
};
render() {
const divStyle = {
color: this.state.fc,
backgroundColor: this.state.bg,
};
return (
<div>
<div style={divStyle}>
<p>Start editing to see some magic happen :)</p>
<Input
parentCallback={this.handleCallback}
parentReset={this.handleReset}
/>
<Result title={this.state.inp} />
<Select colorCallback={this.handleColor} bgCallback={this.handleBg} />
<Range value={this.state.fz} fzCallback={this.handleFz} />
</div>
</div>
);
}
}