trying to learn react, and a bit confused about how to call another component on click..
my button component:
import React from 'react';
import Header from '.././Header.js'
class Login extends React.Component {
render() {
return (
<div className='Login'>
<button id='login' onClick={ Header.incrementCount }>increment</button>
</div>
);
};
}
export default Login;
my class component:
import React from 'react';
import Head from 'next/head'
export default class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 1,
};
}
incrementCount = () => {
this.setState({
count: this.state.count 1
});
};
render() {
return (
<Head>
<title>/{this.state.count}</title>
</Head>
);
}
};
i'm basically just trying to get the title of the page to increment with every click...but im getting no response
CodePudding user response:
You need to pass the function down as a prop to the child, so that the child can see it in its props and call it.
class Login extends React.Component {
render() {
return (
<div className='Login'>
<button id='login' onClick={ this.props.incrementCount }>increment</button>
</div>
);
};
}
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 1,
};
}
incrementCount = () => {
this.setState({
count: this.state.count 1
});
};
render() {
return (
<div>
<Login incrementCount={this.incrementCount} />
<h3>/{this.state.count}</h3>
</div>
);
}
};
ReactDOM.render(<Header />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
CodePudding user response:
There could be multiple approaches to achieve this.
If there is a Parent-Child relationship
For example if Logincomponent
is wrapped under HeaderComponent
and LoginComponent wants to call HeaderComponent's APIs. For that passing method ref as the part of props
is the best way which is explained in above post.
If there is no relation between components
In that case you can store HeaderComponent object reference to some global variable using ref
feature of React and then access it in any component.
Try below code:
import React from "react";
var header;
export default function App() {
return (
<div>
<Header ref={(h) => { header = h; }}></Header>
<Login></Login>
</div>
);
}
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
this.addCount = this.addCount.bind(this);
}
addCount() {
this.setState({
count: this.state.count
});
}
render() {
return (
<div>
Count : {this.state.count}
</div>
)
}
}
class Login extends React.Component {
constructor(props) {
super(props);
}
login() {
header.addCount();
}
render() {
return (
<div>
<button onClick={this.login}>Login</button>
</div>
);
}
}