How to access Component properties into another component file - reactjs

I'm new to react and i've been learning how to solve this error by Accessing properties of a component class to another component class.
import React, { Component } from 'react';
import People from './Properties/People';
import './App.css';
class App extends Component {
// Here I'm trying to access props from People component and print it out.
<div className='one'>
<h1> Bunch of People </h1>
<p> The name is {this.state.Names[1].Person2} </p>
<p> The name is {this.state.Names[2].Person3} </p>
<p> The name is {this.state.Names[0].Person1} </p>
</div>
);
}
}
export default App;
./Properties/People
import { Component } from 'react';
class People extends Component{
constructor(){
super();
this.state = {
Names: [
{ Person1: 'Hetch' },
{ Person2: 'Danny' },
{ Person3: 'Willy' },
{ Person4: 'Tiget' },
{ Person5: 'Leclerc'},
{ Person6: 'Zoel' }]
}}
}
export default People;
Compiled with warnings.
./src/App.js
Line 2: 'People' is defined but never used no-unused-vars
Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.

The way react shares data between components is by props , which is an object.
So you need to call your App component inside your People component and pass the state as props.
Try this inside your people component
<App people={this.state.Names} />
And call this.props.people inside your App component and you will get the Names
more info: https://reactjs.org/docs/components-and-props.html
Hope this help!

Related

How can I refer to another react component?

is there a way to get component's state name, from another component?
I have a component Chat:
import ChatMessage from './ChatMessage'
class Chat extends Component {
state = {
name: 'Bob',
messages: [],
}
getStateName = function(){
return this.state.name
}
}
and another component ChatMessage:
import Chat from './Chat'
class ChatMessage extends Component{
render(){
return(
<p> {Chat.getStateName} </p>
)
}
}
I would like to get as a result 'Bob'.
I was thinking of using a function called getStateName, but it doesn't seem to work. Any idea's how I can fix that?
Ideally state is private and fully controlled by the component. Redux is a library that can be used to manage application wide states via an application store. Refer to redux's getting started to set your app up.
You are on right track to use Components, but you need some changes to look into
here is Stackblitz link for your project
your Chat.js component file will be
import React, { Component } from 'react';
class Chat extends Component {
state = {
name: 'Bob',
messages: []
};
render() {
return <p>{this.state.name}</p>;
}
}
export default Chat;
And ChatMessage.js component will be
import React, { Component } from 'react';
import Chat from './Chat';
class ChatMessage extends Component {
render() {
return <Chat />;
}
}
export default ChatMessage;
Here's a solution that uses a plain ES6 class to store user data, and delegates rendering to a React component.
Either create an instance of the class before accessing it:
class User {
state = {
name: "Bob",
messages: [
"Could you get cucumber from the grocery store?",
"Don't forget the tomatoes, too!",
"Scrap the tomatoes. No tomatoes.",
"Honey, let's get take away instead."
]
};
}
const user1 = new User(); // ← initialising the object instance
const App = () => (
<>
<h1> {user1.state.name} </h1>
<ul>
{user1.state.messages.map((message) => (
<li key={message}>{message}</li>
))}
</ul>
</>
);
export default App;
Or make the state static, which allows you to access it without initialisation:
class User {
static state = { // ← the state object is now static
name: "Bob",
messages: [
"Could you get cucumber from the grocery store?",
"Don't forget the tomatoes, too!",
"Scrap the tomatoes. No tomatoes.",
"Honey, let's get take away instead."
]
};
}
// no need for initialisation
// const user1 = new User();
const App = () => (
<>
<h1> {User.state.name} </h1>
<ul>
{User.state.messages.map((message) => (
<li key={message}>{message}</li>
))}
</ul>
</>
);
export default App;

React alternative coding style with a 'constructor'

Creating a React component the 'standard' way a constructor will run before any rendering and I can use componentDidMount etc to run before the rendering
export class BotShowUI extends Component{
constructor(props) {
super(props)
}
....
My question is in the code below how do I get a constructor type method or another method to run (similar to componentDidMount) before the rendering in the return statement ?
import React, {Component} from 'react';
import PropTypes from 'prop-types';
const BotShowUI = ({ bot, onClick }) => {
return(
<div id={bot.id} onClick={onClick}>
{bot.id} : {bot.text}
</div>
)
}
BotShowUI.propTypes = {
bot: PropTypes.object.isRequired,
onClick: PropTypes.func.isRequired
};
export default BotShowUI;
Currently you cannot. Functional components are stateless. They won't always be, though. https://twitter.com/sebmarkbage/status/658713924607606784

react.js props and state inside multilevel components

I have one app having component structure like below.
Component App Main parent which loads header in all components using {this.props.children}
Component Header
Component Home
Component Dashboard
Component Data
Component DataLoad
App contains Header in render passing some state variables.
Home contains Dashboard which has actions to update the state variables of App to update the Header.
Data contains DataLoad also from here i need to update the state variable of App to update the Header.
For example my App is like
import React from 'react';
import Header from './Header.jsx';
class App extends React.Component {
constructor(props) {
super();
this.state = {
show : '1',
}
this.showHide = this.showHide.bind(this);
}
showHideSearch() {
this.setState(prevState => ({
show: prevState.show == '1' ? '0' : '1',
}));
}
render() {
return (
<div>
<Header show={this.state.show}/>
{this.props.children}
</div>
)
}
}
export default App;
import React from 'react';
import Dashboard from './Dashboard.jsx'
class Home extends React.Component {
constructor(props) {
super();
this.showHide = this.showHide.bind(this);
}
showHide() {
tried this but not working
//this.props.showHideSearch();
}
render() {
return (
<div>// this props show not going to dashboard component
<Dashboard show={this.props.show} showHide= {this.showHide.bind(this)}/>
</div>
)
}
}
export default Home;
If I am understanding your question right, you are wanting to pass your this.showHideSearch function from your App component to its the component in this.props.children - your Home component.
This is easily accomplishable using:
React.cloneElement(this.props.children, {showHideSearch: this.showHideSearch});
Put that in place of where you have this.props.children.
Source - https://stackoverflow.com/a/35102287/6621973
Edit: To update a parent's state, simply pass down a function setting the state from parent to child. There are several examples if you Google "react change parent state", for example: How to update parent's state in React?

Click event in ReactJS error: imports/ui/ParentComponent.jsx:5:16: Unexpected token (5:16)

I am trying to learn Event in ReactJS.
I created 2 components
ChildComponent is
import React, { Component } from 'react';
// App component - represents the whole app
export default class ChildComponent extends Component {
render() {
return (
<button onClick={this.props.onBannerClick}>Click me!</button>
);
}
}
And ParentComponent is
import React, { Component } from 'react';
import ChildComponent from './ChildComponent.jsx'
// App component - represents the whole app
export default class ParentComponent extends Component {
performMagic: function() {
alert('TAADAH!');
},
render() {
return (
<BannerAd onBannerClick={this.performMagic} />
);
}
}
but I got the error
Errors prevented startup:
While building for web.browser:
imports/ui/ParentComponent.jsx:5:16: Unexpected token (5:16)
Your application has errors. Waiting for file change.
I think the error is from
performMagic: function() {
alert('TAADAH!');
},
But I do know what the error is.
By the way, can anybody recommends me good debug tools for ReactJS?
Because you're using the ES6 syntax you'll have to bind the function to the instance using the following approach.
constructor(props) {
super(props)
this.performMagic = this.performMagic.bind(this)
}
This will allow you to use the this keyword in the onClick call
import React, { Component } from 'react';
import ChildComponent from './ChildComponent.jsx'
// App component - represents the whole app
export default class ParentComponent extends Component {
constructor(props) {
super(props)
this.performMagic = this.performMagic.bind(this)
}
performMagic() {
alert('TAADAH!');
}
render() {
return (
<BannerAd onBannerClick={this.performMagic} />
);
}
}
Need to write:
performMagic () {
alert('TAADAH!');
},
You need to use new sintax for functions, when write class which is new sintax.
EDIT: You can use "React Developer Tools" chrome extension and gaearon "redux-devtools" for development.
You need to use the new ES6 syntax when making your React Component a class. Use
performMagic() {
alert('TAADAH!');
}
make sure you don't put a comma after the function

Reactjs Material UI state is undefined on event

I'm building a simple app using react and material ui
Main component
'use strict';
import React from 'react';
import ProjectList from './projectlist';
export default class Application extends React.Component {
constructor(props) {
super(props);
}
changeProject() {
}
render() {
return <div className="row">
<div className="col s3">
<ProjectList
onProjectChangeEvent={this.changeProject}/>
</div>
</div>;
}
}
ProjectList component
'use strict';
import React from 'react';
import Card from 'material-ui/lib/card/card';
import CardHeader from 'material-ui/lib/card/card-header';
import CardText from 'material-ui/lib/card/card-text';
import FlatButton from 'material-ui/lib/flat-button';
import CardActions from 'material-ui/lib/card/card-actions';
// FIXME: Remove when react1.0 is launched
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
export default class ProjectList extends React.Component {
constructor(props) {
super(props);
this.state = {
data: props.data || [],
changeEvent: props.onProjectChangeEvent
};
}
componentDidMount() {
}
openEdit = () => {
console.debug(this.state);
}
render() {
return <Card>
<CardHeader
title="Super Project Title"
subtitle="Super Project Subtitle"/>
<CardText>
Something important
</CardText>
<CardActions>
<FlatButton
label="Edit"
onTouchTap={this.openEdit}/>
</CardActions>
</Card>;
}
}
when I click the FlatButton, the console.debug(this.state) == undefined? How can I communicate with the Application component from the ProjectList component? I want to send the project object back to the Application. Inside the constructor the props exist, same goes for componentDidMount. But in the event it's undefined. How come?
Update
Adding the change suggested by #taylorc93 gives me this error in the console
Uncaught (in promise) Error: http://localhost:3000/app/components/projectlist.js: Unexpected token (31:13)
29 | }
30 |
> 31 | openEdit = () => {
| ^
32 | console.debug(this.state);
33 | }
Define your function as
openEdit() {
console.debug(this.state);
}
Then you can either bind it in the constructor:
constructor(props) {
super(props);
this.openEdit = this.openEdit.bind(this);
}
and reference it normally:
<FlatButton label="Edit" onTouchTap={this.openEdit} />
Or just bind it when you reference it (no changes to the constructor necessary):
<FlatButton label="Edit" onTouchTap={this.openEdit.bind(this)} />
With the ES6 class changes, React no longer automatically binds this to all of your component's methods, just render, the constructor, and the lifecycle methods. https://facebook.github.io/react/docs/reusable-components.html#no-autobinding
Thus, when openEdit is fired, this is not set to your react component. The easiest way to fix this is by using a neat trick with ES6 arrow functions like this:
openEdit = () => {
console.debug(this.state);
}
This takes advantage of the lexical this binding that arrow functions offer and will correctly bind this to your react component. This might be interesting to you for further reading: http://babeljs.io/blog/2015/06/07/react-on-es6-plus/
Hope all of this helps!
Write like this:
openEdit () {
console.debug(this.state);
}

Resources