I googled and found some relevant answers but they don't seem to be complete. eg. react.js don't render until ajax request finish
One of the answer suggest to put if else in template, and I have the following Loader component doing this:
var LoaderWrapper = function (props) {
return (
<div>
{props.loaded ? props.children :
<div className="margin-fixer">
<div className="sk-spinner sk-spinner-wave">
<div className="sk-rect1"></div>
<div className="sk-rect2"></div>
<div className="sk-rect3"></div>
<div className="sk-rect4"></div>
<div className="sk-rect5"></div>
</div>
</div>}
</div>
)
};
Now if I use this wrapper:
<LoaderWrapper loaded={variable!=null}>
<MyComponent variable={variable}/>
</LoaderWrapper>
In MyComponent:
render () {
const {variable} = this.props;
return (<div>{variable.abc}</div>)
}
Problem is that still complains about variable is null.
Also tried the following, complains about the same thing...
<LoaderWrapper loaded={false}>
<MyComponent variable={variable}/>
</LoaderWrapper>
You must be doing something wrong, the following code still works and is based on your above idea
import React, { Component } from 'react';
import { render } from 'react-dom';
var LoaderWrapper = function (props) {
return (
<div>
{props.loaded ? props.children :
<h2> Loading ... </h2>}
</div>
)
};
class MyComponent extends Component {
render() {
const { variable } = this.props;
return (<div>{variable.abc}</div>)
}
}
class MyApp extends Component {
constructor() {
this.state = { loaded: false };
this.changeLoading();
}
changeLoading() {
setTimeout(() => {
this.setState({
loaded: true
})
}, 2000)
}
render() {
return (
<LoaderWrapper loaded={this.state.loaded}>
<MyComponent variable={{ abc: 'This is news' }} />
</LoaderWrapper>
)
}
}
render(<MyApp />, document.getElementById('root'));
Please see here for working example https://stackblitz.com/edit/react-q6wynn?file=index.js
Related
Good day. I'm building a tree of components and want to use functions of root component in other components of tree. I throw function reference through all tree.
Also I use the object if me need get value from the function in not root componet.
Can you help me?
Can you show me how to do this as HOC ?
If it will be not so hard for you show examples on my code.
import React from 'react';
class Page extends React.Component{
Answer = {
value : ''
}
doSomething(){
console.log(this.Answer.value);
console.log('Ready!');
}
render(){
return(
<div>
<div>
<Body
ParentFunc={()=>this.doSomething()}
ParentParameters={this.Answer}
/>
</div>
</div>
)
}
}
export default Page
class Body extends React.Component{
render(){
const{
ParentFunc,
ParentParameters
} = this.props
return(
<div>
<div>
<SomeComponent
ParentFunc={()=>ParentFunc()}
ParentParameters={ParentParameters}
/>
</div>
</div>
)
}
}
class SomeComponent extends React.Component{
getAnswer(){
const{
ParentFunc,
ParentParameters
} = this.props
ParentParameters.value = 'Some text'
ParentFunc()
}
render(){
return(
<div onClick={()=>this.getAnswer()}>
We can?
</div>
)
}
}
I don't believe a Higher Order Component alone will solve your basic issue of prop drilling. A React Context would be a better fit for providing values and functions generally to "want to use functions of root component in other components of tree".
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
In a typical React application, data is passed top-down (parent to
child) via props, but such usage can be cumbersome for certain types
of props (e.g. locale preference, UI theme) that are required by many
components within an application. Context provides a way to share
values like these between components without having to explicitly pass
a prop through every level of the tree.
Start by creating your Context and Provider component:
const QnAContext = React.createContext({
answer: {
value: ""
},
doSomething: () => {}
});
const QnAProvider = ({ children }) => {
const answer = {
value: ""
};
const doSomething = () => {
console.log(answer.value);
console.log("Ready!");
};
return (
<QnAContext.Provider value={{ answer, doSomething }}>
{children}
</QnAContext.Provider>
);
};
Render QnAProvider in your app somewhere wrapping the React subtree you want to have access to the values being provided:
<QnAProvider>
<Page />
</QnAProvider>
Consuming the Context:
Class-based components consume contexts via the render props pattern.
<QnAContext.Consumer>
{({ answer, doSomething }) => (
<SomeComponent doSomething={doSomething} answer={answer}>
We can?
</SomeComponent>
)}
</QnAContext.Consumer>
Functional components can use the useContext React hook
const SomeComponent = ({ children }) => {
const { answer, doSomething } = useContext(QnAContext);
getAnswer = () => {
answer.value = "Some text";
doSomething();
};
return <div onClick={this.getAnswer}>{children}</div>;
};
Here is where using a Higher Order Component may become useful. You can abstract the QnAContext.Consumer render props pattern into a HOC:
const withQnAContext = (Component) => (props) => (
<QnAContext.Consumer>
{(value) => <Component {...props} {...value} />}
</QnAContext.Consumer>
);
Then you can decorate components you want to have the context values injected into.
const DecoratedSomeComponent = withQnAContext(SomeComponent);
...
<DecoratedSomeComponent>We can with HOC?</DecoratedSomeComponent>
Note: The point of doing all this was to move the values and functions that were previously defined in Page into the Context, so they are no longer passed from Page though Body to SomeComponent (or any other children components).
Demo
Sandbox Code:
const QnAContext = React.createContext({
answer: {
value: ""
},
doSomething: () => {}
});
const QnAProvider = ({ children }) => {
const answer = {
value: ""
};
const doSomething = () => {
console.log(answer.value);
console.log("Ready!");
};
return (
<QnAContext.Provider value={{ answer, doSomething }}>
{children}
</QnAContext.Provider>
);
};
const withQnAContext = (Component) => (props) => (
<QnAContext.Consumer>
{(value) => <Component {...props} {...value} />}
</QnAContext.Consumer>
);
class SomeComponent extends React.Component {
getAnswer = () => {
const { doSomething, answer } = this.props;
answer.value = "Some text";
doSomething();
};
render() {
return (
<button type="button" onClick={this.getAnswer}>
{this.props.children}
</button>
);
}
}
const DecoratedSomeComponent = withQnAContext(SomeComponent);
class Body extends React.Component {
render() {
return (
<div>
<div>
<QnAContext.Consumer>
{({ answer, doSomething }) => (
<SomeComponent doSomething={doSomething} answer={answer}>
We can?
</SomeComponent>
)}
</QnAContext.Consumer>
</div>
<div>
<DecoratedSomeComponent>We can with HOC?</DecoratedSomeComponent>
</div>
</div>
);
}
}
class Page extends React.Component {
render() {
return (
<div>
<div>
<Body />
</div>
</div>
);
}
}
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<QnAProvider>
<Page />
</QnAProvider>
</div>
);
}
Based on your current code I am making the assumption that Body does not modify the values of ParentFunc and ParentParameters before passing them down to SomeComponent.
You have a hierarchy
<Page>
<Body>
<SomeComponent>
</Body>
</Page>
and you want to pass props from Page to SomeComponent without going through Body.
You can do this using children
children is a special prop representing the JSX child elements of the component. We make it so that Body renders the children that it got through props:
class Body extends React.Component{
render() {
return(
<div>
<div>
{this.props.children}
</div>
</div>
)
}
}
We set that children prop by using a <SomeComponent/> element inside of the <Body>:
render() {
return (
<div>
<div>
<Body>
<SomeComponent
ParentFunc={() => this.doSomething()}
ParentParameters={this.Answer}
/>
</Body>
</div>
</div>
);
}
Note that you cannot directly modify the value that you got from the parent, which is what you were doing with ParentParameters.value = 'Some text'. If you want to update the state of the parent then you need to do that through your callback function props. So your code should look something like this:
import React from "react";
class Body extends React.Component {
render() {
return (
<div>
<div>{this.props.children}</div>
</div>
);
}
}
class SomeComponent extends React.Component {
state = {
showAnswer: false
};
onClick() {
// update answer in parent
this.props.setAnswer("Some text");
// change state to reveal answer
this.setState({ showAnswer: true });
}
render() {
return (
<div>
{this.state.showAnswer && <div>Answer is: {this.props.answer}</div>}
<div onClick={() => this.onClick()}>We can?</div>
</div>
);
}
}
class Page extends React.Component {
state = {
value: ""
};
render() {
return (
<div>
<div>
<Body>
<SomeComponent
answer={this.state.value}
setAnswer={(answer) => this.setState({ value: answer })}
/>
</Body>
</div>
</div>
);
}
}
export default Page;
I'm attempting to consume a JSON API using fetch; the error mentioned above appears on the following line: **this.state.data.map( (dynamicData,key)=>**
This is my ReactJS code with the error line in bold:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
//constructor
constructor() {
super();
this.state = {
data: [],
}
} //end constructor
componentDidMount(){
return fetch('https://jsonplaceholder.typicode.com/todos')
.then((response)=>response.json())
.then((responseJson)=>
{
this.setState({
data:responseJson.todos
})
console.log(this.state.data)
})
} // end component did mount
render() {
return (
<div>
<h2>Todo:</h2>
<div>
{
**this.state.data.map( (dynamicData,key)=>**
<div>
<span> {dynamicData.userId} </span>
<span> {dynamicData.id} </span>
</div>
)
}
</div>
</div>
);
}
}
export default App;
Could I get some help as to what I'm doing wrong? Thanks in advance
import React, { Component } from "react";
import { render } from "react-dom";
class App extends Component {
state = {
data:[],
url: "https://jsonplaceholder.typicode.com/todos"
};
componentDidMount() {
fetch(this.state.url)
.then(response => response.json())
.then(data => this.setState({ data }));
}
render() {
const { data } = this.state;
data && console.log(data);
return (
<div>
{data &&
data.map(item => <div> Hello User With Id: {item.userId} </div>)}
</div>
);
}
}
render(<App />, document.getElementById("root"));
Your didMount should look like mine also, setState takes a callback so if you wanted to see what the data looked like it would be like this
this.setState({ data }, () => console.log(this.state.data))
In your render it looks like you forgot the parenthesis after the arrow function in map.
render() {
return (
<div>
<h2>Todo:</h2>
<div>
{
this.state.data.map((dynamicData,key)=> (
<div>
<span> {dynamicData.userId} </span>
<span> {dynamicData.id} </span>
</div>
))
}
</div>
</div>
);
}
I'm sorry if this is a frequent question but it's something I'm reallly struggling to understand.
I'm building a basic to-do list app in React.
The container currently contains a form that takes in the information, and adds each item inputted an items array in the state. I then have a 'TaskList' component that takes this state and renders my tasks.
What I want to do is create a separate form component, instead of having the form within my container.
The issue is that if I just copy the code for the form into a new component, the state it will modify is its own, and therefore won't be accessible via the TaskList component to render the list of tasks.
Is there any way to have a component that can update the state of its parent component. My source code is below for reference.
export default class Container extends React.Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
items: []
}
}
handleSubmit(e) {
e.preventDefault();
var itemsArray = this.state.items;
itemsArray.push(e.target.elements.task.value);
this.setState({
items: itemsArray
})
e.target.reset();
}
render() {
return (
<div className="">
<header className="header">TODO</header>
<form onSubmit={this.handleSubmit}>
<input name="task" placeholder="Task"></input>
<button type="submit">Add</button>
</form>
<TaskList data={this.state.items} />
</div>
);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
const TaskList = props => {
var tasks = (props.data).map( (item, key) => { return <Task data={item} key={key} /> })
return(
<ul className="gif-list">
{tasks}
</ul>
);
}
export default TaskList;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
You can do it this way. Pass the parent function that change the state as a props to the form component. In the form handle submit function, call the parent function as this.props.addTodo(todoText).
Container.js
import React, { Component } from 'react';
import TaskList from './TaskList';
import Form from './Form';
export default class Container extends Component {
constructor() {
super();
this.handleAdd = this.handleAdd.bind(this);
this.state = {
items: []
}
}
handleAdd(todoText) {
var itemsArray = this.state.items;
itemsArray.push(todoText);
this.setState({
items: itemsArray
})
}
render() {
return (
<div className="">
<header className="header">TODO</header>
<Form addTodo={this.handleAdd}/>
<TaskList data={this.state.items} />
</div>
);
}
}
Form.js
import React, { Component } from 'react';
export default class Form extends Component {
handleSubmit(e) {
e.preventDefault();
let todoText = e.target.elements.task.value;
if(todoText.length > 0) {
e.target.elements.task.value = '';
this.props.addTodo(todoText);
}else{
e.target.elements.task.focus();
}
}
render() {
return(
<div>
<form onSubmit={(e) => this.handleSubmit(e)}>
<input name="task" placeholder="Task"></input>
<button type="submit">Add</button>
</form>
</div>
);
}
}
TaskList.js
import React from 'react';
const TaskList = props => {
var tasks = (props.data).map( (item, key) => { return <li key={key}>{item}</li> })
return(
<ul className="gif-list">
{tasks}
</ul>
);
}
export default TaskList;
I'm having troubles wrapping my head around this. I'm trying to show/hide text inside one of my components, but I'm not able to do it. I get I was clicked! message so I know the function is being passed down. What am I missing?
Do I also need to declare a visibility CSS declaration, maybe that's what I'm missing?
SnippetList.jsx
import React, { Component, PropTypes } from 'react'
import { createContainer } from 'meteor/react-meteor-data';
import Snippet from './snippet'
import { Snippets } from '../../../api/collections/snippets.js'
class SnippetList extends React.Component {
constructor(props) {
super(props);
this.state = { visible: false }
this.toggleVisible = this.toggleVisible.bind(this);
}
toggleVisible() {
this.setState( { visible: !this.state.visible } )
console.log('I was clicked');
}
renderSnippets() {
return this.props.snippets.map( (snippet) => (
<Snippet
key={snippet._id}
title={snippet.title}
content={snippet.content}
onClick={this.toggleVisible}
/>
));
}
render() {
const snippets = Snippets.find({}).fetch({});
return (
snippets.length > 0
?
<ul>{this.renderSnippets()}</ul>
:
<p>No Snippets at this time</p>
)
}
}
SnippetList.propTypes = {
snippets: PropTypes.array.isRequired,
}
export default createContainer(() => {
Meteor.subscribe('snippets');
return {
snippets: Snippets.find({}).fetch()
};
}, SnippetList);
Snippet.jsx
import React, { Component, PropTypes } from 'react'
export default class Snippet extends React.Component {
render() {
const visible = this.props.toggleVisible
return (
<article>
<header>
<h1 className='Snippet-title'>{this.props.title}</h1>
</header>
<div className={visible ? 'show' : 'hidden'} onClick={this.props.onClick}>
<p className='Snippet-content'>{this.props.content}</p>
</div>
</article>
)
}
}
Snippet.propTypes = {
title: PropTypes.string.isRequired,
content: PropTypes.string.isRequired
// toggleVisible: PropTypes.func.isRequired
}
the issue is you aren't passing the hide part as a prop.
in Snippet you do const visible = this.props.toggleVisible but... toggleVisible isn't passed to your Snippet component thus its always undefined
return this.props.snippets.map( (snippet) => (
<Snippet
key={snippet._id}
title={snippet.title}
content={snippet.content}
onClick={this.toggleVisible}
/>
));
add toggleVisible... aka change to this.
return this.props.snippets.map( (snippet) => (
<Snippet
key={snippet._id}
title={snippet.title}
content={snippet.content}
toggleVisible={this.state.visible}
onClick={this.toggleVisible}
/>
));
you should probably also bind your renderSnippets this to the class as well... meaning add this to your constructor this.renderSnippets = this.renderSnippets.bind(this);
Now to talk about your code, why are you rendering a <ul> as the parent of a <article> ? the child of a ul should be a <li> I would refactor your components to be more like this.
class SnippetList extends React.Component {
constructor(props) {
super(props);
this.state = { visible: false };
this.toggleVisible = this.toggleVisible.bind(this);
this.renderSnippets = this.renderSnippets.bind(this);
}
toggleVisible() {
this.setState( { visible: !this.state.visible } )
console.log('I was clicked');
}
renderSnippets() {
return this.props.snippets.map( (snippet) => (
<Snippet
key={snippet._id}
title={snippet.title}
content={snippet.content}
toggleVisible={this.state.visible}
onClick={this.toggleVisible}
/>
));
}
render() {
const snippets = Snippets.find({}).fetch({});
return (
snippets.length > 0
? <ul>{this.renderSnippets()}</ul>
: <p>No Snippets at this time</p>
)
}
}
export default class Snippet extends React.Component {
render() {
const {toggleVisible: visible} = this.props;
return (
<li>
<article>
<header>
<h1 className="Snippet-title">{this.props.title}</h1>
</header>
<div onClick={this.props.onClick}>
<p className={visible ? 'show Snippet-content' : 'hidden Snippet-content'}>{this.props.content}</p>
</div>
</article>
</li>
)
}
}
We have been experiencing some problems in using react now but it kinda boils to one part of how we have been using react.
How should we have been showing/hiding child components?
This is how we have coded it (this are only snippets of our components)...
_click: function() {
if ($('#add-here').is(':empty'))
React.render(<Child />, $('#add-here')[0]);
else
React.unmountComponentAtNode($('#add-here')[0]);
},
render: function() {
return(
<div>
<div onClick={this._click}>Parent - click me to add child</div>
<div id="add-here"></div>
</div>
)
}
and lately I've been reading examples like it should've been somewhere along this lines:
getInitialState: function () {
return { showChild: false };
},
_click: function() {
this.setState({showChild: !this.state.showChild});
},
render: function() {
return(
<div>
<div onClick={this._click}>Parent - click me to add child</div>
{this.state.showChild ? <Child /> : null}
</div>
)
}
Should I have been using that React.render()? It seems to stop various things like shouldComponentUpdate to cascade to child and things like e.stopPropagation...
I've provided a working example that follows your second approach. Updating the component's state is the preferred way to show/hide children.
Given you have this container:
<div id="container">
</div>
you can either use modern Javascript (ES6, first example) or classic JavaScript (ES5, second example) to implement the component logic:
Show/hide components using ES6
Try this demo live on JSFiddle
class Child extends React.Component {
render() {
return (<div>I'm the child</div>);
}
}
class ShowHide extends React.Component {
constructor() {
super();
this.state = {
childVisible: false
}
}
render() {
return (
<div>
<div onClick={() => this.onClick()}>
Parent - click me to show/hide my child
</div>
{
this.state.childVisible
? <Child />
: null
}
</div>
)
}
onClick() {
this.setState(prevState => ({ childVisible: !prevState.childVisible }));
}
};
React.render(<ShowHide />, document.getElementById('container'));
Show/hide components using ES5
Try this demo live on JSFiddle
var Child = React.createClass({
render: function() {
return (<div>I'm the child</div>);
}
});
var ShowHide = React.createClass({
getInitialState: function () {
return { childVisible: false };
},
render: function() {
return (
<div>
<div onClick={this.onClick}>
Parent - click me to show/hide my child
</div>
{
this.state.childVisible
? <Child />
: null
}
</div>
)
},
onClick: function() {
this.setState({childVisible: !this.state.childVisible});
}
});
React.render(<ShowHide />, document.body);
/* eslint-disable jsx-a11y/img-has-alt,class-methods-use-this */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import todoStyle from 'src/style/todo-style.scss';
import { Router, Route, hashHistory as history } from 'react-router';
import Myaccount from 'src/components/myaccount.jsx';
export default class Headermenu extends Component {
constructor(){
super();
// Initial state
this.state = { open: false };
}
toggle() {
this.setState({
open: !this.state.open
});
}
componentdidMount() {
this.menuclickevent = this.menuclickevent.bind(this);
this.collapse = this.collapse.bind(this);
this.myaccount = this.myaccount.bind(this);
this.logout = this.logout.bind(this);
}
render() {
return (
<div>
<div style={{ textAlign: 'center', marginTop: '10px' }} id="menudiv" onBlur={this.collapse}>
<button onClick={this.toggle.bind(this)} > Menu </button>
<div id="demo" className={"collapse" + (this.state.open ? ' in' : '')}>
<label className="menu_items" onClick={this.myaccount}>MyAccount</label>
<div onClick={this.logout}>
Logout
</div>
</div>
</div>
</div>
);
}
menuclickevent() {
const listmenu = document.getElementById('listmenu');
listmenu.style.display = 'block';
}
logout() {
console.log('Logout');
}
myaccount() {
history.push('/myaccount');
window.location.reload();
}
}