How to make components load only once in React? - reactjs

I am using React to realize following: in the Main page, if users click one button, will load Child page, if not then load another child page.
The problem is the Child component is loading repeatedly because I can check in console that the 'load function' is being printed nonstop. How can I let the child component only load(refresh) once when user clicks the button? Thanks!
In main.jsx:
import {Child} from "../Child";
export const Main = (props) => {
....
if (props.ButtonClicked) {
showPortal = <Child />
} else {
showPortal = <AnotherChild />
}
....
}
in Child.jsx:
export const Child = ()=> {
console.log('load function')
return (<div>test</div>)
}

Not sure what are trying to do because you haven't post your whole code.
But something like this should work.
export default class Comp extends React.Component {
constructor(props) {
super(props);
this.state = {
clicked: false,
};
}
onClickFunction() {
this.setState({
clicked: true,
});
}
render() {
const d = this.state.clicked && <Child />;
return (
<div>
<button onClick={this.onClickFunction.bind(this)}></button>
{d}
</div>
);
}
}
const Child = () => {
console.log("load function");
return <div>test</div>;
};

Related

React Native Pass Parent Method to Child Component

I am trying to pass method from my parent component to child component. My code is correct i think but still it shows the error undefined is not an object(evaluating '_this2.props.updateData') . I don't know whats the issue because i searched the internet a lot and everyone is passing props to child like this. Kindly tell what am i missing
Parent:
class Parent extends React.Component {
updateData = (data) => {
console.log(`This data isn't parent data. It's ${data}.`)
// data should be 'child data' when the
// Test button in the child component is clicked
}
render() {
return (
<Child updateData={val => this.updateData(val)} />
);
}
Child:
class Child extends React.Component {
const passedData = 'child data'
handleClick = () => {
this.props.updateData(passedData);
}
render() {
return (
<button onClick={this.handleClick()}>Test</button>
);
}
}
`class Child extends React.Component {
handleClick = () => {
const passedData = 'child data'
this.props.updateData(passedData);
}
render() {
return (
<button onClick={this.handleClick}>Test</button>
);
}
}`
class Parent extends React.Component {
updateData = (data) => {
console.log(`This data isn't parent data. It's ${data}.`)
}
render() {
return (
<Child updateData={this.updateData} />
);
}
}
and child component: `
class Child extends React.Component {
const passedData = 'child data'
handleClick = () => {
this.props.updateData(passedData);
}
render() {
return (
<button onClick={this.handleClick}>Test</button>
);
}
}
`
You need to pass the function directly, not as a callback
class Parent extends React.Component {
updateData = (data) => {
console.log(`This data isn't parent data. It's ${data}.`)
// data should be 'child data' when the
// Test button in the child component is clicked
}
render() {
return (
<Child updateData={this.updateData} />
);
}
I think you need to pass a function like this. Check out this solution.

How to Set a state of parent component from child component in react js

how do i change the state of parent in child component
I'm trying to create a popover in react
Parent component
class App extends Component {
constructor(props) {
super(props);
this.state = {
status: false,
anchorEl: null
};
}
showpop = () => {
this.setState({ status: !this.state.status });
};
render() {
return (
<React.Fragment>
<p id="popup" onClick={this.showpop}>
Click me
</p>
{this.state.status ? (
<Popup status={this.state.status}>test</Popup>
) : (
""
)}
</React.Fragment>
);
}
}
i just passed the state of status to popover component .
This is the child component
export default class popup extends Component {
constructor(props) {
super(props);
this.state = {
popupStatus: false
};
}
componentWillMount() {
document.addEventListener("click", this.handleclick, false);
}
componentWillUnmount() {
document.removeEventListener("click", this.handleclick, false);
}
handleclick = e => {
if (this.node.contains(e.target)) {
return;
} else {
//here what to do?
}
};
render() {
return (
<React.Fragment>
<Mainbox
status={this.props.status}
ref={node => {
this.node = node;
}}
>
{this.props.children}
</Mainbox>
</React.Fragment>
);
}
}
In the handleclick function else part ,
i tried these
I change the node style display to none but in the window need two clicks to show a popover
you can see the Mainbox component in child is created using styed components library
is there any way to hide the elemet and change the parent state?
You can just pass a method reference to child:
<Popup status={this.state.status} showpop={this.showpop}>test</Popup>
handleclick = e => {
if (this.node.contains(e.target)) {
return;
} else {
this.props.showpop()
}

How to pass spinning bar to another component in ReactJS

I am in a scenario where I have to add a spinning bar in the component say,
List.js
class List extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
//spinning bar should be displayed here
</div>
);
}}
But the spinning bar should be displayed when another method in Actions(i.e redux) is called. So How will I pass this from actions.js to the render component in List.js
Actions.js
export const getList = (listInfo) => dispatch => {
//Spinning should start here
return application.getClientInfo(userInfo).then(
listInfo => {
//spinning should stop here
return dispatch(getListInfo(listInfo))
},
error => {
return dispatch(apologize('Error in getting application'))
}
)
}
getList and ListComponent is called in main.js
main.js
render() {
this.props.getClientApplication(this.props.user);
return (
<div>
<List />
</div>
);
}
So how will I add render method here that is actually to be displayed in list.js? Please help
In your reducer, keep a loading state and dispatch an action to set and clear loading states as and when you want
class List extends Component {
constructor(props) {
super(props);
}
render() {
const { isLoading } = this.props;
return (
<div>
//spinning bar should be displayed here
{isLoading && <Spinner>}
</div>
);
}
}
Actions.js
export const spinner = isLoading => {
return {
type: actionType.SPINNER, isLoading
}
}
export const getList = (listInfo) => dispatch => {
//dispatch loading action
dispatch(spinner(true));
return application.getClientInfo(userInfo).then(
listInfo => {
dispatch(spinner(false))
return dispatch(getListInfo(listInfo))
},
error => {
dispatch(spinner(false))
return dispatch(apologize('Error in getting application'))
}
)
}
Also make sure you aren't dispatching an action in render without using suspense
render() {
this.props.getClientApplication(this.props.user);
return (
<div>
<List isLoading={this.props.isLoading} />
</div>
);
}

Call child component function from parent

How do I call a child component function from the parent component? I've tried using refs but I can't get it to work. I get errors like, Cannot read property 'handleFilterByClass' of undefined.
Path: Parent Component
export default class StudentPage extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
newStudentUserCreated() {
console.log('newStudentUserCreated1');
this.refs.studentTable.handleTableUpdate();
}
render() {
return (
<div>
<StudentTable
studentUserProfiles={this.props.studentUserProfiles}
ref={this.studentTable}
/>
</div>
);
}
}
Path: StudentTable
export default class StudentTable extends React.Component {
constructor(props) {
super(props);
this.state = {
studentUserProfiles: props.studentUserProfiles,
};
this.handleTableUpdate = this.handleTableUpdate.bind(this);
}
handleTableUpdate = () => (event) => {
// Do stuff
}
render() {
return (
<div>
// stuff
</div>
);
}
}
UPDATE
Path StudentContainer
export default StudentContainer = withTracker(() => {
const addStudentContainerHandle = Meteor.subscribe('companyAdmin.addStudentContainer.userProfiles');
const loadingaddStudentContainerHandle = !addStudentContainerHandle.ready();
const studentUserProfiles = UserProfiles.find({ student: { $exists: true } }, { sort: { lastName: 1, firstName: 1 } }).fetch();
const studentUserProfilesExist = !loadingaddStudentContainerHandle && !!studentUserProfiles;
return {
studentUserProfiles: studentUserProfilesExist ? studentUserProfiles : [],
};
})(StudentPage);
My design here is: component (Child 1) creates a new studentProfile. Parent component is notified ... which then tells component (Child 2) to run a function to update the state of the table data.
I'm paraphrasing the OP's comment here but it seems the basic idea is for a child component to update a sibling child.
One solution is to use refs.
In this solution we have the Parent pass a function to ChildOne via props. When ChildOne calls this function the Parent then via a ref calls ChildTwo's updateTable function.
Docs: https://reactjs.org/docs/refs-and-the-dom.html
Demo (open console to view result): https://codesandbox.io/s/9102103xjo
class Parent extends React.Component {
constructor(props) {
super(props);
this.childTwo = React.createRef();
}
newUserCreated = () => {
this.childTwo.current.updateTable();
};
render() {
return (
<div className="App">
<ChildOne newUserCreated={this.newUserCreated} />
<ChildTwo ref={this.childTwo} />
</div>
);
}
}
class ChildOne extends React.Component {
handleSubmit = () => {
this.props.newUserCreated();
};
render() {
return <button onClick={this.handleSubmit}>Submit</button>;
}
}
class ChildTwo extends React.Component {
updateTable() {
console.log("Update Table");
}
render() {
return <div />;
}
}

save react component and load later

I have react component in react native app and this will return Smth like this:
constructor(){
...
this.Comp1 = <Component1 ..... >
this.Comp2 = <Component2 ..... >
}
render(){
let Show = null
if(X) Show = this.Comp1
else Show = this.Comp1
return(
{X}
)
}
and both of my Components have an API request inside it ,
so my problem is when condition is changed and this toggle between Components , each time the Components sent a request to to that API to get same result ,
I wanna know how to save constructed Component which they wont send request each time
One of the ways do that is to handle the hide and show inside each of the child component comp1 and comp2
So you will still render both comp1 and comp2 from the parent component but you will pass a prop to each one of them to tell them if they need to show or hide inner content, if show then render the correct component content, else just render empty <Text></Text>
This means both child components exist in parent, and they never get removed, but you control which one should show its own content by the parent component.
So your data is fetched only once.
Check Working example in react js: https://codesandbox.io/s/84p302ryp9
If you checked the console log you will find that fetching is done once for comp1 and comp2.
Also check the same example in react native below:
class Parent extends Component {
constructor(props)
{
super(props);
this.state={
show1 : true //by default comp1 will show
}
}
toggleChild= ()=>{
this.setState({
show1 : !this.state.show1
});
}
render(){
return (
<View >
<Button onPress={this.toggleChild} title="Toggle Child" />
<Comp1 show={this.state.show1} />
<Comp2 show={!this.state.show1} />
</View>
)
}
}
Comp1:
class Comp1 extends Component
{
constructor(props) {
super(props);
this.state={
myData : ""
}
}
componentWillMount(){
console.log("fetching data comp1 once");
this.setState({
myData : "comp 1"
})
}
render(){
return (
this.props.show ? <Text>Actual implementation of Comp1</Text> : <Text></Text>
)
}
}
Comp2:
class Comp2 extends Component {
constructor(props) {
super(props);
this.state = {
myData2: ""
}
}
componentWillMount() {
console.log("fetching data in comp2 once");
this.setState({
myData2: "comp 2"
});
}
render() {
return (
this.props.show ? <Text>Actual implementation of Comp2</Text> : <Text></Text>
)
}
}
I think, you should move all your logic to the main component (fetching and saving data, so you component1 and component2 are simple dumb components. In component1 and component2 you can check "does component have some data?", if there isn't any data, you can trigger request for that data in parent component.
Full working example here: https://codesandbox.io/s/7m8qvwr760
class Articles extends React.Component {
componentDidMount() {
const { fetchData, data } = this.props;
if (data && data.length) return;
fetchData && fetchData();
}
render() {
const { data } = this.props;
return (
<div>
{data && data.map((item, key) => <div key={key}>{item.title}</div>)}
</div>
)
}
}
class App extends React.Component{
constructor(props){
super(props);
this.state = {
news: [],
articles: [],
isNews: false
}
}
fetchArticles = () => {
const self = this;
setTimeout( () => {
console.log('articles requested');
self.setState({
articles: [{title: 'article 1'}, {title: 'articles 2'}]
})
}, 1000)
}
fetchNews = () => {
const self = this;
setTimeout(() => {
console.log('news requested');
self.setState({
news: [{ title: 'news 1' }, { title: 'news 2' }]
})
}, 1000)
}
handleToggle = (e) => {
e.preventDefault();
this.setState({
isNews: !this.state.isNews
})
}
render(){
const { news, articles, isNews} = this.state;
return (
<div>
<a href="#" onClick={this.handleToggle}>Toggle</a>
{isNews? (
<News data={news} fetchData={this.fetchNews} />
): (
<Articles data={articles} fetchData={this.fetchArticles} />
)}
</div>
)
}
}

Resources