I have a state in which i have
I had initialized my data state as null
For whole code visit
https://codeshare.io/5zMyXD
Calling aixos api request on componentDidMount
axios.post("http://localhost/axios1/index.php",data)
.then(res=>this.setState({data:res.data},
()=>console.log(this.state.data)))
Getting this on state
{id: "1", name: "vivek", fname: "modi", mobile: "9024555623", photo: "http://localhost/axios1/uploaded/student/rhinoslider-sprite.png"}
fname: "modi"
id: "1"
mobile: "9024555623"
name: "vivek"
photo: "http://localhost/axios1/uploaded/student/rhinoslider-sprite.png"
<input defaultValue={this.state.data.name} />
how to set these values in it's input like input for name input for fname
{id: "1", name: "vivek", fname: "modi", mobile: "9024555623", photo: "http://localhost/axios1/uploaded/student/rhinoslider-sprite.png"}
fname: "modi"
id: "1"
mobile: "9024555623"
name: "vivek"
photo: "http://localhost/axios1/uploaded/student/rhinoslider-sprite.png"
<input defaultValue={this.state.data.name} />
Just use name from state
as if the object you mentioned is state then you can directly access state keys from state
like
this.state.name || this.state.mobile
You need to show your code in order to get better help but
If you have a correct state you can change values like this:
<input type="text" name="fname" value={this.state.data.name}>
But your state is null and the code you showed has problem, you need to fill your state correctly, in your class you can write:
State={name:"test"}
And it will work fine. Hope this can help you
update now write this:
{this.state.data && this.state.data.name
&& ( < input defaultValue={this.state.data.name} /> )}
You can set like call your axios request through
componentDidMount(){
axios.post("http://localhost/axios1/index.php",data)
.then(res=>this.setState({data:res.data},
()=>console.log(this.state.data)))
}
Suppose you are getting this in your state
state={
data:{
id: "1",
name: "vivek",
fname: "modi",
mobile: "9024555623",
photo: "http://localhost/axios1/uploaded/student/rhinoslider-sprite.png"
}
}
and then render it as
render(){
const {name,fname} = this.state.data?this.state.data:"";
return(
<div>
<input defaultValue={this.state.name} />
<input defaultValue={this.state.fname} />
</div>
);
}
Change this in your code, line no 31
this.setState({res.data},()=>console.log(this.state))
Related
I know its basic but i am stuck with the following bug or error. Need help
I am trying to use simple array method to return value on console and on screen using basic methods in react but it is giving me undefined error on console.
Following are the code of React of APP.js.
import React from 'react'
function App(){
const [employees, setemployees] = React.useState([{
id: 1,
fullName: "Bob Jones",
designation: "JavaScript Developer",
gender: "male",
teamName: "TeamA"
},
{
id: 2,
fullName: "Jill Bailey",
designation: "Node Developer",
gender: "female",
teamName: "TeamA"
},
{
id: 3,
fullName: "Gail Shepherd",
designation: "Java Developer",
gender: "female",
teamName: "TeamA"
}]);
console.log(employees.fullName)
return(
<main>
<h1>{employees.fullName}<h1/>
</main>
)
}
export default App
Output:
Console: Undefined
On Screen: empty
Need help how to solve this error.
I tried different known methods like moving into components but does not work. I am expecting to show data on screen and on console.
it must be error. because you can't access employees.fullName. it must be at least employees[0].fullName to access first object inside employees array.
console.log(employees[0].fullName);
if you want to render all names as an h1 you can do this.
{employees.map(employee => <h1 key={employee.id}>{employee.fullName}</h1>)}
The error message you're encountering is likely "Cannot read property 'fullName' of undefined." This is because employees is an array of objects and not a single object, so trying to access a property like fullName directly on employees will not work.
To fix this, you need to loop over the employees array and render each individual employee. One way to do this is by using the map function to iterate over the array and create a new array of elements for each employee.
employees[0].fullName
should do it
Can you please give more details? btw, have you tried to write something like:
<div>
<ol>
{employees.map(employee => { <li key={employee.fullName}>{employee.fullName}</li>)}
</ol>
</div>
this is my code in react.
const [value, setValue] = React.useState<CountriesEntityData | null>({
id: '',
name: '',
regions: [
{
id: '',
name: '',
districts: [
{
id: '',
name: '',
locations: [{ id: '', city: '', division: '', street: '' }],
},
],
},
],
})
I try this code in resolving this problem
value?.regions?.name
can anyone give me tutorial link in dealing in this kind of situation thank you.
If you just wanna use the first element you can do:
let name = value?.regions?.[0]?.name;
If if you wanna search the object based on an id, then I think there is a find function on the array which you can use like that:
let name = value?.regions?.find((elm) => elm.id == 'myId')?.name;
a regions in value is array.
and not answer value?.regions?.name .
because regions contains objects and objects contain property ```name'''
for this kind of problems, simply you can use log and see your variable in console
console.log(your const);
then by looking at your console, easily you can see how to address your array to get your desired result.
Now assuming that you want to extract the nested names in the object,
for two arrays inside each other, you should use two MAP which are nested.
this can give you the idea:
{ListOfData.map((item, index) => (
<div key={index}>
<h1>{item.title}</h1>
{item.content.map((c, i) => (
<div key={i}>
<h3>{c.title}</h3>
<h3>{c.description}</h3>
<hr />
</div>
))}
</div>
))}
I cannot get my reactjs component to reflect the actual changes in state on a checkbox. Could anyone kindly assist or point out what is wrong with my code below.
This is my state
state = {
data: {
name: "",
address: "",
city: "",
country: "",
mobile_number: "",
description: "",
has_conference: false,
star_rating: "",
},
errors: {},
};
This handle checkbox method
toggleChange = () => {
this.setState({
has_conference: !this.state.data["has_conference"],
});
};
And finally the checkbox code in render method
<label>
<input
type="checkbox"
has_conference={this.state.data["has_conference"]}
onChange={this.toggleChange}
/>
Conferencing
</label>
There are two things to correct in your code.
1: In toggleChange you dont change this.state.data.has_conference, but you change this.state.has_conference which is not exists in initial state. For changing this.state.data.has_conference you need to do following in your toggleChange function:
let data = this.state.data
data.has_conference = !data.has_conference
this.setState({data})
2: In you need to bind your this.state.data.has_conference value to the checked attribute. In code you need to write:
<input type="checkbox" onChange={this.toggleChange} checked={this.state.data.has_conference}
Hope this help.
I have multiple checkboxes, when I click on a "Select All/None" checkbox, it works, all the checkboxes are checked, but I want to be able to check each checkbox one by one. My problem is that they all use the same state. So if I click on a checkbox to only check this one, it is checking all the other ones.
So my question is : Is it possible to concatenate an id to a state ?
There are my states :
isAllTablesChecked: false,
isAllReportsChecked: false,
isTableChecked: false,
isReportChecked: false,
tables: [
{id: 1, name: 'Accounts'},
{id: 2, name: 'Asset Types'},
{id: 3, name: 'Assets'},
{id: 4, name: 'Bank Transactions'}
],
report: [
{id: 5, name: 'Aged Payables by Contact'},
{id: 6, name: 'Aged Receivables by Contact'},
{id: 7, name: 'Balance Sheet'},
{id: 8, name: 'Bank Statement'}
]
In a map, below :
const tables = this.state.tables.map(table =>
<div>
<Input
type="checkbox"
name={table.name}
id={this.state.isTableChecked}
checked={this.state.isTableChecked}
onClick={this.checkTables}
/>
<b> {table.name} </b>
</div>
)
const reports = this.state.reports.map(report =>
<div>
<Input
type="checkbox"
name={report.name}
id={this.state.isReportChecked}
checked={this.state.isReportChecked}
onClick={this.checkReports}
/>
<b> {report.name} </b>
</div>
)
For the id line in the <Input> tag, is it possible to do something like :
id={this.state.isTableChecked+tables.id}
Thanks for your help.
I found a solution to my issue.
As I said in my response to Jeremy Harris, I used the checked property inside the JSON data of my state array badly.
Here is the link to the solution, it worked for me :
https://medium.com/#tariqul.islam.rony/multiple-checkbox-handling-by-react-js-84b1d49a46c6
Hope that will help you, I will put this topic as resolved.
I have a method in a react Contact List component where I am returning another component. I have got it working but am curious if there is a better way to structure how I am using the key.
Specifically - I'm asking about this line of code from the method below (data is hard coded as sample to get started):
return <ShortContact contact={contact} key={contact.id}/>
Here is the code in context:
_getContacts() {
let contactList = [
{
id: 1,
fName: "aaa",
lName: "aaaaa",
imgUrl: "http://brainstorminonline.com/wp-content/uploads/2011/12/blah.jpg",
email: "aaa#aaaa.com",
phone: "999999999999"
},
{
id: 2,
fName: "bbbbb",
lName: "bbbbbbb",
imgUrl: "https://media.licdn.com/mpr/mpr/shrinknp_200_200/bbb.jpg",
email: "bbb#bbb-bbb.com",
phone: "888888888888"
},
{
id: 3,
fName: "Number",
lName: "Three",
imgUrl: "http://3.bp.blogspot.com/-iYgp2G1mD4o/TssPyGjJ4bI/AAAAAAAAGl0/UoweTTF1-3U/s1600/Number+3+Coloring+Pages+14.gif",
email: "three#ccccc.com",
phone: "333-333-3333"
}
];
return contactList.map((contact) => {
"use strict";
return <ShortContact contact={contact} key={contact.id}/>
});
}
ShortContact Component Render:
class ShortContact extends React.Component {
render() {
return (
<div >
<li className="contact-short well whiteBG">
<img className="contact-short-thumb" src={this.props.contact.imgUrl}/>
<p className="contact-short-name">{this.props.contact.fName}</p><br />
<p className="contact-short-email">{this.props.contact.email}</p>
</li>
</div>
);
}
}
I struggled with how to make it work and not get the warning Warning: Each child in an array or iterator should have a unique "key" prop. However I am wondering if the syntax or structure is valid and if it should be refactored.
There is nothing wrong with this code. The key is required so that react knows how to render the children nodes. In fact your implementation is exactly what react requires the programmer to do. Now the details of which key to use and such can be changed, but it looks like you have the most performant solution already.
The main requirement is that the key is unique so as long as contact.id is always unique (which if its coming from a database then it will be) then you are fine.
Alternatively you can use an index on your map for the key but I wouldn't really recommend it (i'll explain below after the code snippet).
contactList.map((contact, i) => {
return <ShortContact contact={contact} key={i}/>
});
Personally I think your approach is the best approach because it can prevent additional renders. What I mean is for instance when a new contact is returned from the server every contact row would be re-rendered because the index in the array for each contact is different (assuming you aren't treating it like a stack)... The different index with new contact data at that index would cause the re-render. Because contact.id is a static number if the data for that contact hasn't changed then react wont re-render it.
The use of a unique key is required. In your example, using the id is ideal. see the following for more information:
https://facebook.github.io/react/docs/lists-and-keys.html