My Objective is to display the name which is inside the object. here is the snippet attached for your reference.
it contains:
{
id: "12497wewrf5144",
name: "ABC",
isVisible: "false"
}
I have tried in this way:
import React, { Component } from "react";
class Demo extends Component {
constructor(props: Props) {
super(props);
this.state = {
demo: {}
};
}
componentDidMount() {
axios.get('/api/random')
.then(res => {
this.setState({demo: res.data})
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<div>
<h1>{this.state.demo.name}</h1>
</div>
);
}
}
export default Demo;
But i'm not getting the value of name.
We use map for multiple objects in array, but do we need to map even for single array?
i have tried giving like "this.state.demo[0].name", but this one also not working
Can anyone help me in this query?
Assuming your API response is like following
data =[
{id: "12497wewrf5144", name: "ABC", isVisible: "false"},
{id: "12497wewrf5255", name: "CBD", isVisible: "true"}
];
Render Response Data
class First extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{id: "12497wewrf5144", name: "ABC", isVisible: "false"},
{id: "12497wewrf5255", name: "CBD", isVisible: "true"}
];,
};
}
render() {
return (
<ul>
{this.state.data.map(d => <li key={d.name}>{d.name}</li>)}
</ul>
);
}
}
Related
I have a simple array of objects but I can't seem to update state with the filtered values. If you console.log() the filteredData variable, the data is filtering correctly. However if I use the same variable inside setState() the filtered results aren't returning when console logging the people array. Does anyone know why this is happening? I'd also like to be able to re-render the list of filtered results. Do I need to use .map() inside the setState() method?
Thanks in advance.
import React from 'react';
import ReactDOM from 'react-dom';
import { v4 as uuidv4 } from 'uuid';
class App extends React.Component {
constructor(props) {
super(props);
this.handleSearch = this.handleSearch.bind(this);
this.state = {
people: [
{ id: uuidv4(), name: 'dave' },
{ id: uuidv4(), name: 'bryan' },
{ id: uuidv4(), name: 'abi' },
{ id: uuidv4(), name: 'chris' },
],
text: ''
}
}
handleSearch(e) {
const value = e.target.value.toLowerCase()
this.setState((prevState) => ({ text: value }));
}
render() {
const { people, text } = this.state;
const filteredData = people.filter((person) => {
return person.name.toLowerCase().includes(text.toLowerCase())
})
return (
<div>
<input type="text" name="searchPeople" placeholder="Search..." onChange={ this.handleSearch } />
<ul>
{
filteredData.map((person) => (<li key={ person.id }>{ person.name }</li>))
}
</ul>
</div>
);
}
}
const root = document.querySelector('#appRoot');
ReactDOM.render(<App />, root);
Edit both setState to retain the previous state unchanged properties this way:
this.setState({
...this.state,
people: filteredData,
});
this.setState({ ...this.state, filters: { text: value } });
Like #Cybershadow mentioned in the comment above, setState is asynchronous. And your log is being triggered before the value in this.state.people changes i.e. logged the previous state value. You can use a setState callback function to make use of the changed data state after a setState update is completed. And to use the setState callback, you need to pass the callback function as an second argument to the setState() method. In your case something like this:
this.setState(
{people: filteredData},
()=>console.log(this.state.people) //callback
);
More on React's setState() method.
#mjwals as setState is non concurrent the refreshed state will not be accessible quickly, so you can compose a callback work in the setState strategy inside the callback you will get the refreshed state, so from that point you can do other activity with the refreshed information. genuinely take a look at the code underneath
import React from 'react';
import "./styles.css";
import { v4 as uuidv4 } from 'uuid';
class App extends React.Component {
constructor(props) {
super(props);
this.handleSearch = this.handleSearch.bind(this);
this.state = {
people: [
{ id: uuidv4(), name: 'dave' },
{ id: uuidv4(), name: 'bryan' },
{ id: uuidv4(), name: 'abi' },
{ id: uuidv4(), name: 'chris' }
],
text: ''
}
}
handleSearch(e) {
const value = e.target.value.toLowerCase()
this.setState({ text: value }, () => {
const { people, text } = this.state;
const filteredData = people.filter((person) => {
return person.name.toLowerCase().includes(text.toLowerCase())
})
this.setState({ people: filteredData })
});
}
render() {
const { people } = this.state;
return (
<div>
<p>Please enter a input to search</p>
<input type="text" name="searchPeople" placeholder="Search..." onChange={this.handleSearch} />
<ul>
{people.map((person) => <li key={person.id}>{person.name}</li>)}
</ul>
</div>
);
}
}
export default App;
I am new to the React, And I want to using react-data-table-component to display my fetch data from Api in a sorted table. but the issue I do not know the correct method to use the react-data-table-component.and the instruction of react-data-table-component do not include such example.
Following is my code:
I was trying to put offence or this.state.offence direct into data, but show nothing, anyone please give me some advises about the correct way to use this or some other way create sorted table to show this data.and there is link to the react-data-table-component a link:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { off } from 'rsvp';
import DataTable from 'react-data-table-component';
const columns = [
{
name: 'Offences',
selector: 'Offences',
sortable: true,
},
{
name: 'Year',
selector: 'year',
sortable: true,
right: true,
},
];
class SignInForm extends Component {
constructor() {
super();
this.state = {
email: '',
password: '',
offence:[],
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleClick =this.handleClick.bind(this);
this.handleLogin =this.handleLogin.bind(this);
}
handleClick(){
const url ="https://xxxxxxxxxx.sh/offences";
fetch(url)
.then(response => {
console.log(response.clone().json())
console.log(response.headers.get('Content-Type'))
if (response.ok) {
return response.clone().json();
} else {
throw new Error('Something went wrong ...');
}
})
.then((res) =>{
console.log(res)
this.setState({
offence: [res]
});
}) // get just the list of articles
console.log(this.state.offence);
}
render() {
return (
<button className="FormField__offence" onClick{this.handleClick}>offence</button>
</div>
<div>
<DataTable
title="Offences"
columns={columns}
data={this.state.offence}
/>
</div>
</form>
</div>
);
}
}
export default SignInForm;
I was expecting one column decent table show
const columns = [
{
name: 'Offences',
selector: 'Offences',
sortable: true,
}
];
class SignInForm extends React.Component {
constructor() {
super();
this.state = {
email: '',
password: '',
offence: [],
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
const url = "https://xxxxxxxx.sh/offences";
fetch(url)
.then(response => {
if (response.ok) {
return response.clone().json();
} else {
throw new Error('Something went wrong ...');
}
})
.then((res) => {
this.setState({
offence: res.offences.map((item,id) => ({id, Offences: item}))
});
}) // get just the list of articles
}
render() {
console.log(this.state.offence)
return (
<div className="App">
<button
className="FormField__offence"
onClick={this.handleClick}>offence</button>
<DataTable
title="Offences"
columns={columns}
data={this.state.offence}
/>
</div>
);
}
}
Live Link
Replace this,
this.setState({
offence: [res]
});
with this,
this.setState({
offence: res
});
In your case this is res from API call
{offences: Array(88)}
offences: (88) ["Advertising Prostitution", ... "Weapons Act Offences", "Weapons Act Offences - Other"]
__proto__: Object
So you can get offences like this,
this.setState({
offence: res.offences
});
I have a main component Resume and a child called Header:
class Resume extends Component {
constructor(props) {
super();
this.state = {
data: {}
}
}
componentDidMount() {
this.setState( this.state = data);
}
render() {
return (
<div className="Resume">
<Header data={this.state.header} />
<Skills data={this.state.skills} />
</div>
);
}
}
export default Resume;
class Header extends Component {
render() {
return (
<div className="header">
<h1>{JSON.stringify(this.props.data.title)}</h1>
</div>
);
}
}
My simple sample data so far is:
{
"header": {
"title": "Tim Smith's Resume"
},
"skills": [
{"name": "HTML", "duration": 14}
]
}
Why am I getting: TypeError: Cannot read property 'title' of undefined
No need to use JSON#stringify your title property is already a string.
In your componentDidMount is not like that we are setting state. Try to use
componentDidMount()
const data = {}; // Define data or get it like you want
this.setState({
...data
});
}
In your constructor where you initialize your state. You have to do this.state = { header: {}, skills: {} } not what you done.
It looks like you're not setting the state of the <Resume/> component correctly. Try the following adjustment:
componentDidMount() {
// This will set the `data` field of your component state, to the
// value of the `data` variable.
this.setState({ data : data });
}
I managed to add Item to the list but can't render it.
My App.js:
class App extends Component {
constructor(props) {
super(props);
this.state = {
recipes: [{
...sample data...
}]
}
}
createRecipe(recipe) {
this.state.recipes.push({
recipe
});
this.setState({ recipes: this.state.recipes });
}
render() {
...
export default App;
and my RecipeAdd:
export default class RecipeAdd extends Component {
constructor(props) {
super(props);
this.state = {
url: '',
title: '',
description: '',
error: ''
};
}
...event handlers...
onSubmit = (e) => {
e.preventDefault();
if (!this.state.url || !this.state.title || !this.state.description) {
this.setState(() => ({ error: 'Please provide url, title and description.'}));
} else {
this.setState(() => ({ error: ''}));
this.props.createRecipe({
url: this.state.url,
title: this.state.title,
description: this.state.description
});
}
}
render () {
return (
<div>
...form...
</div>
)
}
}
In React dev tools I see the recipe is added with 'recipe'. How should I change my createRecipe action to add new recipe properly? :
It looks like you're wrapping the recipe in an extra object. You can see in your screenshot that index 3 has an extra recipe property.
It should be more like this -- just .push the recipe object directly:
createRecipe(recipe) {
this.state.recipes.push(recipe);
this.setState({ recipes: this.state.recipes });
}
Even better would be to not mutate the state object directly, by using concat instead:
createRecipe(recipe) {
this.setState({
recipes: this.state.recipes.concat([recipe])
});
}
I am new to react and attempting to get the React Data Grid working with some test data - Why would I be getting an error in the rowGetter function that this.state is undefined? I can't find an example that works anywhere.
import React, { PropTypes, Component } from 'react';
import ReactDataGrid from 'react-data-grid';
class FilterGrid extends Component {
static propTypes = {
columns: PropTypes.array,
rows: PropTypes.array
};
constructor (props) {
super(props)
this.state = {
columns: [],
rows: []
}
}
componentDidMount() {
this.setState((prevState, props) => ({
rows: [
{key: 'd1', lname: 'Doe', quantity: 3},
{key: 'd2', lname: 'Simmons', quantity: 97},
{key: 'd3', lname: 'Walters', quantity: 6}
],
columns: [
{name: "Quantity", key: "quantity"},
{name: "Last Name", key: "lname"}
]
}));
}
rowGetter(i) {
return this.state.rows[i];
}
render() {
return (<ReactDataGrid
columns={this.state.columns}
rowGetter={this.rowGetter}
rowsCount={this.state.rows.length}
minHeight={500} />);
}
}
export default FilterGrid;
Because you forgot to bind the rowGetter, bind it in the constructor:
constructor (props) {
super(props)
this.state = {
columns: [],
rows: []
}
this.rowGetter = this.rowGetter.bind(this); //here
}
As per DOC:
You have to be careful about the meaning of this in JSX callbacks. In
JavaScript, class methods are not bound by default. If you forget to
bind this.methodName and pass it to event, this will be undefined
when the function is actually called. This is not React-specific behavior; it is a part of how functions work in JavaScript.
You've got to bind the callback or you don't have access to this:
render() {
return (<ReactDataGrid
columns={this.state.columns}
rowGetter={this.rowGetter.bind(this)}
rowsCount={this.state.rows.length}
minHeight={500} />);
}
However, binding like this will re-bind each time the render is called. It is better to bind in the constructor or make an arrow function method:
constructor:
constructor (props) {
super(props)
this.state = {
columns: [],
rows: []
}
this.rowGetter = this.rowGetter.bind(this);
}
arrow function:
rowGetter = (i) => {
return this.state.rows[i];
}