Getting props via state object - reactjs

I am trying to get props via state object.
import React, { Component } from 'react';
import Counter from './counter';
class Counters extends Component {
state = {
counters: [
{id:1, value:1},
{id:2, value:2},
]
};
render() {
return(
<div>
this.state.counters.map(counter => (
<Counter key={counter.id} value={counter.value}/>))}
</div>)
}
}
export default Counters;
import React, { Component } from 'react';
class Counter extends Component {
state = {
value: this.props.value
};
constructor(){
super();
}
render() {
console.log(this.props);
return (
<div>
</div>
);
}
}
export default Counter;
Why can't I get props within state object? I am seeing props in render.
I am getting TypeError: Cannot read property 'value' of undefined.
Can someone show me how to pass props correctly to the state object. I have seen props passed this way by other coders.
Thanks,
Rob.

You need to pass props to super and define the state in the constructor or remove the constructor and use state directly.
CODESANDBOX
import React, { Component } from "react";
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
value: this.props.value
};
}
render() {
console.log(this.props);
return <div>{this.state.value}</div>;
}
}
export default Counter;
or CODESANDBOX
import React, { Component } from "react";
class Counter extends Component {
state = {
value: this.props.value
};
render() {
console.log(this.props);
return <div>{this.state.value}</div>;
}
}
export default Counter;

Related

How to add additional api to a fetch component in React JS

There are 2 separate components that fetch data through api. The code below is for the first component and then there is another component that fetch other data of the same company through another api and the code of that one is exactly the same except the api link. How to fetch the data from the other api in this component so there is no need for 2 different components.
import React, { Component, Fragment } from 'react'
import axios from 'axios'
class CompanyProfile extends Component {
constructor(){
super();
this.state={
Company:[]
}
}
componentDidMount(){
axios.get('http://localhost:3000/link').then(response =>{
**/////////for example axios.get('http://localhost:3000/link2') added here.**
this.setState({Company:response.data});
});
}
render() {
const cp = this.state.Company;
const CompanyView = contact.map((cp,i)=>{
**/////then mapped here.**
return <div>
<p>{cp.name}</p>
<p>{cp.type}</p>
<p>...other data</p>
**//// and then displayed here <p>{cp.CompanyProducts.data}</p>**
</div>
});
return (
<div>
{CompanyView}
</div>
)
}
}
export default CompanyProfile
I am not sure about your question. We can use container and presentational components.
A container does data fetching and then renders its corresponding sub-component. That’s it.
Refactor the CompanyProfile component to a stateless presentational component. Pass the company data from the remote API server to it from the container component.
So that we can reuse the CompanyProfile component.
CompanyProfile.jsx:
import React, { Component } from 'react';
class CompanyProfile extends Component {
render() {
const { campany } = this.props;
const CompanyView = campany.map((cp, i) => {
return (
<div>
<p>{cp.name}</p>
<p>{cp.type}</p>
<p>...other data</p>
<p>{cp.CompanyProducts.data}</p>
</div>
);
});
return <div>{CompanyView}</div>;
}
}
export default CompanyProfile;
Parent1.tsx:
import React, { Component } from 'react';
import axios from 'axios';
import CompanyProfile from './CampanyProfile';
export default class Parent extends Component {
constructor(props) {
super(props);
this.state = {
company: [],
};
}
componentDidMount() {
axios.get('http://localhost:3000/link').then((response) => {
this.setState({ company: response.data });
});
}
render() {
return <CompanyProfile company={this.state.company} />;
}
}
Parent2.jsx:
import React, { Component } from 'react';
import axios from 'axios';
import CompanyProfile from './CampanyProfile';
export default class Parent2 extends Component {
constructor(props) {
super(props);
this.state = {
company: [],
};
}
componentDidMount() {
axios.get('http://localhost:3000/link2').then((response) => {
this.setState({ company: response.data });
});
}
render() {
return <CompanyProfile company={this.state.company} />;
}
}

what is best way to get props in React / React Native

I'm really regarding props in React/React-Native. I have a parent view. In this view I'm getting the user data from a LocalStorage.['
import React, { Component } from 'react';
import { Container, Content, View } from 'native-base';
import NutrionalToolbar from '../../components/NutrionalToolbar';
import { AsyncStorage } from 'react-native';
export default class LogsScreen extends Component {
state = {
user: '',
}
componentWillMount() {
this._bootstrapAsync();
}
_bootstrapAsync = async () => {
const user = await AsyncStorage.getItem('user');
this.setState({ user: JSON.parse(user) })
};
render() {
return (
<Container>
<NutrionalToolbar user={this.state.user} />
</Container>
);
}
}
Now inside the NutrionalToolbar component I have this.
import React, { Component } from 'react';
import { View } from 'native-base';
class NutrionalToolbar extends Component {
constructor(props) {
super(props)
console.log(this.props) // This renders an empty user object
}
render() {
console.log(this.props) // This renders the user object with values
return (
<View>
</View>
);
}
}
export default NutrionalToolbar;
How can I get this.props values inside the constructor. I'm getting the values inside render method. Why isn't working inside the constructor?
I would recommend looking into the componentDidUpdate lifecycle hook because, even if you could access the initial user prop in the constructor, you wouldn't be able to access updates to that prop in the constructor.
import React, { Component } from 'react';
import { View } from 'native-base';
class NutrionalToolbar extends Component {
componentDidUpdate() {
console.log(this.props) // This will always log the current props
}
render() {
return (<View></View>);
}
}
export default NutrionalToolbar;

How to pass data from one component to another ReactJS

I have two components. The first has state initialized:
import React from 'react';
class One extends React.Component {
constructor(props) {
super(props);
this.state = {
data: 'hi'
}
}
render() {
return (
<div prop={this.state.data}>{this.state.data}</div>
);
}
}
export default One;
import React from 'react';
class Two extends React.Component {
render() {
return (
<div>{this.prop}</div>
);
}
}
export default Two;
The first component prints out the state of data. How would I pass that value into my second component as a read only value and render it?
To pass the value in the second component, you have to first import it in your first component and pass the value as prop.
For example, your code might look like this:
import React from 'react';
import Two from './Two' // I am assuming One.js and Two.js are in same folder.
class One extends React.Component {
constructor(props) {
super(props);
this.state = {
data: 'hi'
}
}
render() {
return (
<div>
<div>{this.state.data}</div>
<Two value={this.state.data} />
</div>
);
}
}
export default One;
And then in the Two.js you can access the value as below:
import React from 'react';
class Two extends React.Component {
render() {
return (
<div>{this.props.value}</div>
);
}
}
export default Two;
Now, let's say, you are using your component One in App or anywhere. Whenever you will use <One/> you will get following in the browser:
hi
hi
You must call this 'Two' component into 'One' like this
One Component:
render() {
return (
<Two myProp={this.state.data} />
)
}
You can call this whatever u wish (myProp)
And read this in 'Two' component:
render() {
return (
<div>Received data from parent Component: {this.props.myProp}</div>
)
}
Before you call 'Two' component into 'One' you must import that file
import Two from './path/to/component';
Just add the following code in One component render method and pass the data as props which is read-only
import React from 'react';
import Two from '/components/Two'
class One extends React.Component {
constructor(props) {
super(props);
this.state = {
data: 'hi'
}
}
render() {
return (
<div prop={this.state.data}>{this.state.data}</div>
<Two data={this.state.data} />
);
}
}
export default One;
Then In component Two to access data add following code
import React from 'react';
class Two extends React.Component {
constructor(props){
super(props)
}
render() {
return (
<div>{this.props.data}</div>
);
}
}
export default Two;
Props will hold the object transferred from parent element
One.js
import React from 'react';
import Two from './two'
class One extends React.Component {
constructor(props) {
super(props);
this.state = {
data: 'hi'
}
}
render() {
return (
<div>{this.state.data}
<Two dto={this.state} /></div>
);
}
}
export default One;
Two.Js
import React from 'react';
class Two extends React.Component {
render() {
return (
<div>Component Two data: {this.props.dto.data}</div>
);
}
}
export default Two;

'Items' is not defined error when passing value to another component

I am getting ./src/App.js Line 27: 'Items' is not defined react/jsx-no-undef
while trying to pass state to a another component
import React, { Component } from 'react';
import axios from 'axios'
class App extends Component {
// Added this:
constructor(props) {
super(props);
// Assign state itself, and a default value for items
this.state = {
items: []
};
}
componentWillMount() {
axios.get('https://api.opendota.com/api/proMatches').then(res => {
this.setState({ items: res.data });
});
}
render() {
return (
<div className="app">
<Items items={this.state.items} />
</div></blink></blink>
);
}
}
export default App;
You are not trying to use a component called Items without importing it first:
<Items items={this.state.items} />
Every component that you use must be imported first:
import { Items } from "DIRECTORY"
Errors:- (1) import Items component (2) use componentDidMount() instead of componentWillMount() (3) use ternary operator in JSX this.state.items.length > 0 for displaying items after getting response
import React, { Component } from 'react';
import axios from 'axios';
import Items from './Items';
class App extends Component {
// Added this:
constructor(props) {
super(props);
// Assign state itself, and a default value for items
this.state = {
items: []
};
}
componentDidMount() {
axios.get('https://api.opendota.com/api/proMatches').then(res => {
this.setState({ items: res.data });
});
}
render() {
return (
<div className="app">
{
this.state.items.length > 0 ?
<Items items={this.state.items} /> : null
}
</div></blink></blink>
);
}
}
export default App;
App is top component and Items is child component.To use any child component or pass any kind props or state ,it has to be imported first .
There can be another issue to it since you are using state and if the child component Items is rerendered due to any change ,then state of your APP component will also reset.

How to use map on multi objects array in React

This is child component as i can you Props here
Child Component:
import React from "react";
const PeopleList = props => {
console.log("child Props :", props.data);
const list = props.data.map(item => item.name);
return <React.Fragment>{"list"}</React.Fragment>;
};
export default PeopleList;
Main Component:
import React, { Component } from "react";
import { connect } from "react-redux";
import { fetchPeople } from "../actions/peopleaction";
import PeopleName from "../containers/peopleName";
class Main extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
this.props.dispatch(fetchPeople());
}
render() {
const { Error, peoples } = this.props;
console.log("data", peoples);
return (
<div className="main">
{"helo"}
<PeopleName data={peoples.results} />
</div>
);
}
}
const mapStateToProps = state => {
return {
peoples: state.peoples.peoples,
error: state.peoples.error
};
};
export default connect(mapStateToProps)(Main);
If i iterate the props multi objects array i can face Map is not define issue;
I need to iterate the props.data multi objects array in child component and i get object from Redux store. once component loaded the redux store.
can you please some one help me on this.
you can find whole code below mentioned
Try this It works in your codesandbox.
{peoples.results && <PeopleName data={peoples.results} />}

Resources