reactjs insert in handle variable state update - reactjs

I'm new to reactjs and am creating a volume bar.
I update my state with my value and I'd like to enter it in handleclick () {}; so I take updated state and insert it into my function setVolume ();
Is there another way for me to enter my setstate into handleclick (); ?
import React from 'react'
import Slider from 'react-rangeslider'
import 'react-rangeslider/lib/index.css'
import './css/Volume.css'
class VolumeBar extends React.Component
constructor(props, context) {
super(props, context)
this.state = {
volume: 0
}
}
handleOnChange = (value) => {
this.setState({
volume: value
})
}
handleClick(volume) {
window.DZ.player.setVolume()
}
render() {
let { volume } = this.state
console.log(volume);
return (
<div className="VolumeBar">
<Slider value={volume} orientation="horizontal" onChange= {this.handleClick} />
</div>
);
}
}
export default VolumeBar

Have you tried like that?
<Slider value={volume} orientation="horizontal" onChange=this.handleOnChange} />
handleOnChange = (e) => {
this.setState({
volume: e.target.value
})
To set the current volume?

handleOnChange = (value) => {
this.setState({
volume: value
})
window.DZ.player.setVolume(value)
}
thank you i solved it like this.

Related

calling function in React SetState gives error that userName is unlabelled why?

import React,{Component} from 'react'
class Formhandler extends Component {
constructor(props) {
super(props)
this.state = {
userName:""
}
}
changer=(event)=>{
this.setState(()=>{
userName : event.target.value
})
}
render()
{
return(
<div>
<label>UserName</label>
<input type="text" value={this.state.userName} onChange={this.changer}/>
</div>
)
}
}
export default Formhandler
You are getting the error because of invalid syntax.
Update changer function
changer = (event) => {
this.setState({ userName: event.target.value });
};
You need to return an object inside the setState function but you are not that's the source of issue(syntax error).
use a function inside setState when your new state value would depend on your previous state value, where the function passed inside the setState will receive previous state as argument
changer = (e) => {
this.setState((prevState) => ({
userName : e.target.value
})
);
}
pass an object to update the state, use this when it doesn't depend on your previous state value.
changer = (e) => {
this.setState({ userName: e.target.value });
};
import React from "react";
class Formhandler extends React.Component {
constructor(props) {
super(props);
this.state = {
userName: "",
};
}
changer(event) {
this.setState(() => ({
userName: event.target.value,
}));
}
render() {
return (
<div>
<label>UserName</label>
<input
type="text"
value={this.state.userName}
onChange={this.changer.bind(this)}
/>
</div>
);
}
}
export default Formhandler;
It will work, compare your version and this

Update values of edited inputs

I am using react-admin framework and I am trying to update values of my input dynamically.
In my custom component, I have the onChange() method which looks like this:
onChange = (value) => {
this.setState({ currentForm: this.props.record });
const { updated_src, name, namespace, new_value, existing_value } = value;
this.setState({ currentForm: updated_src });
}
First I am setting that the state currentForm has the original unedited values that are stored in this.props.record. After that I am setting that the state has new value updated_src. That variable stores the object with the new edited values. Both objects this.props.record and updated_src have same keys.
Later in render() I have this field:
{this.props.record && <JsonInput src={this.props.record} name={null} displayDataTypes={false} displayObjectSize={false} onEdit={this.onChange} />}
However if I do console.log(this.state.currentForm); in the onChange() method, it returns an empty array instead of the object with updated values of the field.
My whole component:
import React, { Component, Fragment } from 'react';
import { fetchUtils, CardActions, EditButton, Button, List, Datagrid, Edit } from 'react-admin';
import Drawer from '#material-ui/core/Drawer';
import JsonInput from 'react-json-view';
import { Field } from 'redux-form';
import EditIcon from '#material-ui/icons/Edit';
import IconKeyboardArrowRight from '#material-ui/icons/KeyboardArrowRight';
import { SimpleForm } from 'ra-ui-materialui/lib/form';
const divStyle = {
width: '400px',
margin: '1em'
};
export default class JsonEditButton extends Component {
constructor(props, context) {
super(props, context);
this.state = { showPanel: false , currentForm: []};
}
onChange = (value) => {
//that works
this.setState({ currentForm: this.props.record }, () => {
const { updated_src, name, namespace, new_value, existing_value } = value;
/* sets the updated values to state */
this.setState({ currentForm: value.updated_src });
});
}
handleClick = () => {
this.setState({ showPanel: true });
};
handleCloseClick = () => {
this.setState({ showPanel: false });
};
render() {
const { showPanel } = this.state;
return (
<div>
<Button label="Upravit JSON" onClick={this.handleClick}>
<EditIcon />
</Button>
<Fragment>
<Drawer
anchor="right"
open={showPanel}
onClose={this.handleCloseClick}
>
<div>
<Button label="Zavřít" onClick={this.handleCloseClick}>
<IconKeyboardArrowRight />
</Button>
</div>
<div style={divStyle}>
{this.props.record && <JsonInput src={this.props.record} name={null} displayDataTypes={false} onKeyPressUpdate={true} displayObjectSize={false} onEdit={this.onChange} />}
</div>
</Drawer>
</Fragment>
</div>
);
}
};
Any ideas why this code is not working and how to solve this issue?
Thank you in advance.
onChange = (value) => {
this.setState({ currentForm: this.props.record },()=>{
console.log("---currentForm------ >",
this.state.currentForm,this.props.record)
this.callFn(value)
});
}
callFn = (value) => {
const { updated_src, name, namespace, new_value, existing_value } = value;
this.setState({ currentForm: updated_src },()=>{
console.log("---->newData",this.state.currentForm,updated_src)
});
}
try this way ,i think it should help,
just check this console you will get ,why your array is not updating
The React setState() method is asynchronous and only completes after your onChange() handler has completed!

how to make a 'number' component in react native

I want to make a 'number' component which accepts numbers on input.
I tried to make it, but it is not working.
Here the code-
import React, { Component } from 'react';
import { TextInput } from 'react-native';
constructor(props)
{
super(props);
this.state = {
text: ''
};}
handleInputChange = (text) => {
if (/^\d+$/.test(text)) {
this.setState({
text: text
});
}
}
const NumberInput = (props) => {
return (
<TextInput
keyboardType='numeric'
onChangeText={this.handleInputChange}
value={this.state.text}
/>
)
}
export { NumberInput };
You don't have access to this in functional component, you need to define it as class based component,
class NumberInput extends Component{
constructor(props){
super(props);
this.state = {
text: ''
};
}
handleInputChange = (text) => {
if (/^\d+$/.test(text)) {
this.setState({
text: text
});
}
}
render(){
return (
<TextInput
keyboardType='numeric'
onChangeText={this.handleInputChange}
value={this.state.text}
/>
)
}
}
Update
You can also try this,
<TextInput
keyboardType='numeric'
onChange={this.handleInputChange} //onChange instead of onChangeText
value={this.state.text}
/>
And your function should be,
handleInputChange = (e) => {
if (/^\d+$/.test(e.target.value)) {
this.setState({
text: e.target.value
});
}
}
Reference to this change.
Also, you can use Number() function to check if the input is a number. It not, it will return NaN
you should use the class component when to use the constructor and use super or use and used hock function with useState in react
class NumberInput extends Component{
constructor(props){
super(props);
this.state = {
text: ''
};
}
handleInputChange = (text) => {
if (/^\d+$/.test(text)) {
this.setState({
text: text
});
}
}
render(){
return (
<TextInput
keyboardType='numeric'
onChangeText={this.handleInputChange}
value={this.state.text}
/>
)
}
}
or using the following shape when used the function component
import useState from'react'
function NumberInput (){
const [text, setText] = useState('');
handleInputChange = (text) => {
if (/^\d+$/.test(text))(setText(text)) ;
}
}
return (
<TextInput
keyboardType='numeric'
onChangeText={this.handleInputChange}
value={text}
/>
)
}
}

setting state using usestate doesn't call render method

I am trying to update the state of a class using useState(), but when I call the set function the render method of the class doesn't get called.
Also when I call the set function useEffect is called twice.
const InputSlider = (state) => {
const [value, setValue] = useState({
sliderValue: 0
});
const handleSliderChange = (event, newValue) => {
setValue(prevState => ({
...prevState,
sliderValue: newValue
}))
}
useEffect(() => {
console.log("state updated ", value)
});
return(
<Slider
onChange={handleSliderChange}
defaultValue={0}
//value ={value}
getAriaValueText={valuetext}
aria-labelledby="discrete-slider"
valueLabelDisplay="auto"
min={state.state.min}
max={state.state.max}
step={state.state.step}
/>
);
}
class App extends Component {
constructor(){
super();
this.state = {
sliderValue: 0
}
}
render(){
return(
<div className ="slider">
<InputSlider state = { this.state } />
</div>
)
}
}

How to use dynamically created classes in react components

I have a class of this form:
export default class FixedMem {
constructor(totalMem){
this._totalMem = totalMem
}
get totalMem(){
return this._totalMem
}
addMem(mem){
this._totalMem += mem
}
}
I import it into my react component like this :
import Fixed from '../somewhere'
If i want to create a new classes with varying parameters based on input from a textbox and display its values. How do i call its methods from inside the render method ?. This somewhat illustrates my problem
class fixedBlock extends Component {
constructor(){
super()
this.state = {
"textInput":"",
"totalMem":0,
"fixed":null
}
}
handleInputChanged(e){
this.setState({
"textInput":e.target.value
})
}
handleButtonPressed(){
this.setState({"fixed":new Fixed(parseInt(this.state.textInput))})
}
incrementButtonPressed(){
this.state.fixed.addMem(2)
}
render(){
return(
<div>
<input type="button" onClick={this.handleInputChanged} value=
{this.state.textInput}>
<button onClick={this.handleButtonPressed}>create</button>
<button onClick={this.incrementButtonPressed}> increment </button>
<p>{this.state.fixed.totalMem}</p>
</div>
)
}
}
this doesn't work, another approach i had to solve this problem was using closures, so inside my react component :
class fixedBlock extends Component{
constructor(){//stuff here}
FixedMem () {
var FixedObj = null
return {
initFixed: function (totalMem) {
FixedObj = new Fixed(totalMem, divisions)
},
totalMem: function () {
return FixedObj.totalMem
},
increment: function(){
FixedObj.addMem(2)
}
render(){//stuff here}
}
How do i even use this in the render method ?
There are several issues with your code example. Missing closing tags and rebinding of methods missing.
Here's an example of dynamically usage of a class instance in a React component. However I can not recommend to use this approach. This is mainly as proof of concept.
class MyValue {
constructor(val) {
this._val = parseInt(val, 10) || 0;
}
get total() {
return this._val;
}
set total(val) {
this.val = val;
}
add(val) {
this._val += val;
}
subtract(val) {
this._val -= val;
}
}
Here's the React component
class Block extends React.Component {
constructor() {
super();
this.state = {
textInput: "",
myValue: new MyValue()
};
}
handleInputChanged(e) {
this.setState({
textInput: e.target.value
});
}
handleButtonPressed() {
this.setState({ myValue: new MyValue(this.state.textInput) });
}
incrementButtonPressed() {
this.state.myValue.add(2);
this.forceUpdate(); /* React does not know the state has updated, force update */
}
render() {
return (
<div>
<input type="number" step="1" onChange={this.handleInputChanged.bind(this)} />
<button onClick={this.handleButtonPressed.bind(this)}>create</button>
<button onClick={this.incrementButtonPressed.bind(this)}>increment</button>
<p>{this.state.myValue.total}</p>
</div>
);
}
}
As an alternative approach. You could use a pattern where you separate logic from presentation. Here's an example using function as child. The Calculator handles the calculation and Presentation uses the calculator and present the GUI.
class Calculator extends React.Component {
constructor() {
super();
this.state = {value: 0};
}
add(value){
this.setState(prevState => ({value: prevState.value + value}));
}
subtract(value){
this.setState(prevState => ({value: prevState.value - value}));
}
set(){
this.setState(prevState => ({value: parseInt(prevState.input, 10) || 0}));
}
input(value){
this.setState({input: value});
}
render() {
return this.props.children(
{
value: this.state.value,
add: this.add.bind(this),
subtract: this.subtract.bind(this),
set: this.set.bind(this),
input: this.input.bind(this),
});
}
}
const Presentation = props => (
<Calculator>
{ ({value,add,subtract,set,input}) => (
<div>
<button onClick={() => add(2)}>add 2</button>
<button onClick={() => subtract(3)}>subtract 3</button>
<input type="number" step="1" onChange={e => input(e.target.value)} />
<button onClick={set}>set</button>
<p>{value}</p>
</div>)
}
</Calculator>);
The problem with the first attempt is that you are mutating a Component's state without letting React know about it. You need to use setState() or forceUpdate(). One way to still have FixedMem manage your state while letting React know could be:
class FixedBlock extends Component {
constructor(props) {
super(props);
this.state = {
textInput: '',
totalMem: 0
};
this.fixedMem = new FixedMem(0);
this.sync = this.sync.bind(this);
}
sync() {
const totalMem = this.fixedMem.totalMem;
this.setState({ totalMem });
}
handleInputChanged(evt) {
this.setState({ textInput: evt.target.value });
}
handleButtonPressed() {
this.fixedMem = new FixedMem(parseInt(this.state.textInput));
this.sync();
}
incrementButtonPressed() {
this.fixedMem.addMem(2);
this.sync();
}
render() {
return (
<div>
<input type="text" onChange={this.handleInputChanged.bind(this)} />
<button onClick={this.handleButtonPressed.bind(this)}>create</button>
<button onClick={this.incrementButtonPressed.bind(this)}>increment</button>
<p>{this.state.totalMem}</p>
</div>
);
}
}

Resources