React.js - How do I uniquely identify a field within a dynamically generated component? - javascript

I am currently creating a form that has an unknown number of sensor fields within it. I've gotten the front end working beautifully. However, now I want to grab the user info out of those dynamically generated component fields and I can't figure out how. Here is where I'm generating the components:
{this.state.sensors.map((item, i) => (
<UpdateSensorInfo
key={i}
sensorName={item.sensorName}
sensorLowerLimit={item.sensorLowerLimit}
sensorUpperLimit={item.sensorUpperLimit}
/>
))}
And here is the actual component itself:
import React, { Component } from "react";
import "./updateSensorInfo.css";
class UpdateSensorInfo extends Component {
render() {
return (
<div>
<div className="sensorInfoFrame">
<div className="sensorFieldBody">
<label className="sensorTextFieldLabel">Sensor Name:</label>
<input
type="text"
name="text"
placeholder=""
className="sensorTextField"
defaultValue={this.props.sensorName}
required
/>
</div>
<div className="sensorFieldBody">
<label className="sensorTextFieldLabel">Sensor Upper Limit:</label>
<input
type="number"
name="text"
placeholder=""
className="sensorTextField"
defaultValue={this.props.sensorUpperLimit}
required
/>
</div>
<div className="sensorFieldBody">
<label className="sensorTextFieldLabel">Sensor Lower Limit:</label>
<input
type="number"
name="text"
placeholder=""
className="sensorTextField"
defaultValue={this.props.sensorLowerLimit}
required
/>
</div>
</div>
</div>
);
}
}
export default UpdateSensorInfo;
I would like to uniquely identify each text field within each generated component. How can I do this?

For anyone who has a similar situation, I have found a solution that works. There is a way to use the key that is created for each of the components within each component. use the following as an id or name for the input element:
id={`${this._reactInternalFiber.key}-additionalNameHere`}
This uses the key and will allow you to loop over the inputs within the components.

Related

onChange Input field is not change in react js edit update operation

onChange Input field is not change in react js edit update operation. all value fetch using API php. but if click in input field and enter some word not editable so give any solution. may be this issue using map function. if it is possible without map function.
Full Code share plz scroll down the page
enter image description here
all code show onChange Input field is not change in react js edit update operation
import React,{useState, useEffect} from 'react';
import axios from 'axios';
import { useParams } from 'react-router-dom';
//import './App.css';
const EditUser=()=>{
//function Home() {
// const navigate = useNavigate();
const {id} = useParams();
console.log(id);
// console.log("jjjjjj");
// alert(id);
const[titlecourse,settitlecourse]=useState("");
const[listshow,setlistshow]=useState("");
console.log(titlecourse);
const [userdata,setData]=useState ([]);
useEffect(()=>{
fetch(`https://www.example.com/jasonfile/wherecond.php?cid=${id}`).then((result)=>{
result.json().then((resp)=>{
// console.warn("result",resp)
console.log(resp)
setData(resp.data);
})
})
},[])
console.log(userdata);
// show array
return (
<div className="container">
<h1>Edit User {userdata.titlecourse}</h1>
<form >
{
userdata.map((item)=>
<div>
<div class="row mb-3">
<label for="inputEmail3" class="col-sm-2 col-form-label">titlecourse </label>
<div class="col-sm-10">
<input type="text" class="form-control"
name = "titlecourse"
value={item.titlecourse}
//value={titlecourse}
//placeholder={item.titlecourse}
onChange={(e)=>{settitlecourse(e.target.value)}}
/>
</div>
</div>
<div class="row mb-3">
<label for="inputPassword3" class="col-sm-2 col-form-label">listshow</label>
<div class="col-sm-10">
<input type="text" class="form-control"
name = "listshow"
value={item.listshow}
onChange={(e)=>{setlistshow(e.target.value)}}
/>
</div>
</div>
</div>
)
}
<button type="submit" class="btn btn-primary">Sign in</button>
</form>
</div>
);
}
export default EditUser;
all code show onChange Input field is not change value in react js edit update operation
output show in image
enter image description here
In order to see a value change in the input fields, you need to set the value prop as the state variables.
<div class="col-sm-10">
<input type="text" class="form-control"
name = "titlecourse"
value={titlecourse}
onChange={(e)=>{settitlecourse(e.target.value)}}
/>
</div>

I'm getting an error using React: "Invalid DOM property `for`. Did you mean `htmlFor`"

I'm creating a simple CRUD app using React for my front-end, and I'm having trouble with this error:
app.js:21988 Warning: Invalid DOM property `for`. Did you mean `htmlFor`?
Here's my code:
import React, { Component } from 'react';
import axios from 'axios';
export default class Add extends Component {
constructor()
{
super();
this.state={
blogs_name:''
}
}
render() {
return (
<div>
<form>
<div className="form-group">
<label for="blogs_name">Title</label>
<input
type="text"
className="form-control"
id="blogs_name"
value={this.state.blogs_name}
/>
</div>
<button type="submit">Submit</button>
</form>
</div>
);
}
}
I assume that it has to do something with the for property in my label.
Any help is appreciated.
When using React, you can't use the for keyword in JSX, since that's a javascript keyword (remember, JSX is javascript so words like for and class can't be used because they have some other special meaning!)
To circumvent this, React elements use htmlFor instead (see React docs for more information).
So, your render function should be (I only replaced for with htmlFor):
render() {
return (
<div>
<form onSubmit={this.onSubmit} >
<div className="form-group">
<label htmlFor="blogs_name">Title</label>
<input type="text" className="form-control" id="blogs_name"
value={this.state.blogs_name}
onChange={this.onChangeBlogsName} />
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
);
}
Replace for="" with htmlFor=""
In your case change this
<label for="blogs_name">Title</label>
To this
<label htmlFor="blogs_name">Title</label>
for is a reserved word in JavaScript this is why when it comes to HTML attributes in JSX you need to use something else, React team decided to use htmlFor respectively. You can check the list of attributes from here
Short answer, Remove
for="blogs_name"
In your case.

Whats the proper way to have a form submit data in a stateless react component?

I have a stateless react component that is a little pop up. It takes some data from the user, and passes that back to its parent, where it executes the work.
What is the best way for this component to have a handleSubmit() function, that takes the user input, and sends it back to the parent?
import React, { Component } from "react";
import "../../../node_modules/bulma/css/bulma.css";
const Transfer = (props, token, web3) => {
return (
<div className="modal is-active">
<div className="modal-background" onClick={props.onClick} />
<div className="modal-card">
<section className="modal-card-body">
<div className="content">
<h1 className="title"> Transfer Tokens </h1>
<p className="has-text-danger">
Requires that you are the owner of the token you are transferring
</p>
<p className="subtitle">How it works</p>
<p className="">
Enter the ID of the token you want to transfer, the address to
whom its going to, and thats it!
</p>
//problem area
<form onSubmit={props.onClickSubmit}>
<label htmlFor="text">Address to recieve token</label>
<input
name="Address"
className="input is-info "
required="true"
/>
<label htmlFor="number">Token ID</label>
<input
className="input is-info"
name="Token ID"
type="number"
required="true"
/>
<a className="button is-pulled-right">Submit</a>
</form>
</div>
</section>
<footer className="modal-card-foot is-clearfix">
<a className="button" onClick={props.onClick}>
Cancel
</a>
</footer>
</div>
</div>
);
};
export default Transfer;
I pass in as a prop, onClickSubmit, in my parent component, and that contains the logic for what I'm trying to do.
Very new to stateless react components
It will be difficult to accomplish what you want with a stateless component since you cannot use either refs or state in a stateless component. You can think of a stateless component as a pure function that returns a piece of UI depending on the props you give it.
You could instead use a stateful component and e.g. store the input values in state and call the onClickSubmit prop function with this state when the user submits the form.
If you want to build stateless forms component, I send you a lib that I'm working on:
react-distributed-forms
This allow you to build your Transfer Component this way, (pay attention to use Input instead of input and Button instead of button):
import React, { Component } from "react";
import "../../../node_modules/bulma/css/bulma.css";
import { Input, Button } from "react-distributed-forms";
const Transfer = (props, token, web3) => {
return (
<div className="modal is-active">
<div className="myForm">
<label htmlFor="text">Address to receive token</label>
<Input name="Address" className="input is-info " required="true" />
<label htmlFor="number">Token ID</label>
<Input
className="input is-info"
name="Token ID"
type="number"
required="true"
/>
<Button name="submit" className="button is-pulled-right">
Cancel
</Button>
</div>
</div>
);
};
export default Transfer;
And then in your parent Component, wherever it is in the hierarchy, you simply do:
<Form onSubmit={({ name }) => { console.log(name); }} onFieldChange={({ name, value} ) => { console.log(name, value); }}>
...whatever
<Transfer />
...whatever
</Form>
onFieldChange will receive every input change.
onSubmit will receive the attribute "name" on the Button when you click it.
react-distributed-forms use React context API, so you don't have to pass directly props, it just works. Is built for really dynamic forms...

ReactJS props are updated, but field is not re-rendered

I have been playing around with fields in React, but am running into the issue where a text input is not updating (whilst the properties are). I have tried to do it through a class/state component, but to no avail. I was kind-of hoping to be able to make specific form-only components that are completely cut-off from stores. Can anyone point me in the right direction?
import React from 'react';
export default (props) => {
function editProjectNameChanged(event, syntheticEvent) {
debugger;
props.editProject.name = syntheticEvent.target.value;
}
return (
<div className="col-xs-5 col-md-5">
<form>
<div className="form-group">
<label htmlFor="management-projects-name">Project name</label>
<input type="text" className="form-control" id="management-projects-name"
value={props.editProject.name}
onUserInput={editProjectNameChanged.bind(null, event)}
placeholder="Project name" />
</div>
</form>
</div>
);
}
Thanks in advance.. This whole form thing is more difficult than I thought it would!
You shouldn't change the props in the child. That is a good job for the state. It's not a good idea to update props because parent component is not notified of the change and the state is more useful because when you call setState() the component is redraw. Something like that (I haven't tested it)
import React from 'react';
export class YourComponent extends React.Component{
constructor(){
this.state = {
name: this.props.editProject.name
};
}
editProjectNameChanged(event, syntheticEvent) {
this.setState({
name: syntheticEvent.target.value
});
}
render(){
return <div className="col-xs-5 col-md-5">
<form>
<div className="form-group">
<label htmlFor="management-projects-name">Project name</label>
<input type="text" className="form-control" id="management-projects-name"
value={props.editProject.name}
onUserInput={editProjectNameChanged.bind(this, event)}
placeholder="Project name" />
</div>
</form>
</div>;
}
}
You shouldn't mutate props the way you do it from within a component. If you do not want your component do manage the state, it should instead accept a callback as a prop, that it would call on user input.
The parent component would then decide whether or not, and how, to update the value, and pass it back to your component as a prop.
<input value={ props.value } onChange={ e => props.onChange(e.target.value) } />
Mutating directly the props object has no effect since version 0.13. You can find here the blog post explaining why this behaviour was introduced

in React.js data-reactid is breaking html text input?

Hi so my React component renders in the html and works with one catch.
The Catch is "data-reactid=".0.0"" this breaks the input and prevents you from being able to type in it. As soon as i remove/change this the input works again.
My React Component:
/** #jsx React.DOM */
var React = require('../../../../node_modules/react/react.js');
// react component DateBox will return a date time that updates every 50 miliseconds and appends it to a div with an id of 'date_box'
var GoogleSearchBox = React.createClass({
GetValueFromGoogleSearchInput: function(event){
var GoogleSearch = document.getElementById("google_search_input");
var UserSearchQuery = GoogleSearch.value.toString().replace(/ /g,"+");
var GET = "http://google.com/#q=" + UserSearchQuery;
window.open(GET, '_blank');
},
//rendering the html elements with the state.clock
render: function() {
return (
<div className="google_search">
<input type="text" value="" placeholder="Type here to search google" name="google_search_input" id="google_search_input">
</input>
<div>
<button id="google_search_button" onClick={this.GetValueFromGoogleSearchInput}></button>
</div>
</div>
);
}
});
//rendering with react to put onto the html
module.exports = GoogleSearchBox;
How it renders in html:
<div id="google_search_box">
<div class="google_search" data-reactid=".0">
<input type="text" value="" placeholder="Type here to search google" name="google_search_input" id="google_search_input" data-reactid=".0.0">
<div data-reactid=".0.1">
<button id="google_search_button" data-reactid=".0.1.0"></button>
</div>
</div>
</div>
Your text field is not responding to user input because you created a Controlled Component by manually setting the value prop.
An <input> with value set is a controlled component. In a controlled
<input>, the value of the rendered element will always reflect the
value prop.
If you would like to set a default value but allow the text field to respond to user input, consider setting the defaultValue prop instead.
<input type="text" defaultValue="" placeholder="Type here to search google" name="google_search_input" id="google_search_input">

Categories