How to pass a click handler to a child component - javascript

I'm trying to pass a click handler function to a child component but I cant figure out why its not working.
I tried making my click handler into a lambda function, binding it to the parent component, and making my onClick in the child component a lambda function but nothing seems to work.
Parent Component
import React from 'react';
import NavMenuButton from './navMenuButton.js';
export default class NavBar extends React.Component {
constructor(props) {
super(props);
this.state = {
navBarOpen: true
};
this.toggleNavbar = this.toggleNavbar.bind(this);
}
toggleNavbar() {
console.log('Toggled!');
this.setState({
navBarOpen: this.state.navBarOpen ? false : true
});
}
render() {
return (
<NavMenuButton
handleClick={this.toggleNavBar}
navBarOpen={this.state.navBarOpen}
/>
);
}
}
Child Component
import React from 'react';
export default class NavMenuButton extends React.Component{
constructor(props){
super(props)
}
render(){
const styles = {
navButton: this.props.navBarOpen
? {fontSize:26, cursor:'pointer', userSelect:'none'}
: {fontSize:26, cursor:'pointer', userSelect:'none'}
}
return(
<div>
<span
style={styles.navButton}
onClick={this.props.handleClick}
>
{'\u2630'}
</span>
{this.props.navBarOpen
? <p>its open</p>
: <p>its closed</p>}
</div>
);
}
}
This configuration is what I thought should work, but if I log the props in navMenuButton to the console, handleClick is undefined which really confuses me

toggleNavBar !== toggleNavbar - case sensitivity is very important :)

Related

ReactJS: setState from outside [duplicate]

This question already has answers here:
How to update the state of a sibling component from another sibling or imported component in REACT
(3 answers)
Closed 1 year ago.
This is my App.js
import React from 'react';
import './App.css'
import Tools from './components/class/Tools'
import Loading from './components/inc/Loading'
export default class App extends React.Component {
componentDidMount() {
Tools.showLoading();
}
render() {
return (
<div className="App">
<Loading />
</div>
)
}
}
Loading.js:
import React from 'react'
export default class Loading extends React.Component {
constructor(props) {
super(props)
this.state = {
display: 'none'
}
}
render() {
return (
<div className="loading" style={{display: this.state.display}}>
<span></span>
</div>
)
}
}
I want change display of Loading from Tools.js:
export default class Tools extends React.Component {
static showLoading(){ // or non-static
Loading.setState ...
}
}
How I can access and setState variable from another class or function or outside?
Your Loading and Tools components are siblings, so it is harder to pass data between them.
You should pull the state out to the parent App component, then you can pass in the setState callback method and the state.loading variable into the Tool and Loading components as a prop.
Or you can re-use your Loading component within all the other components, like so:
export default class Tool extends React.Component {
constructor(props) {
super(props)
this.state = {
loading: true
}
}
render() {
return (
<Loading isloading={loading}>
<div>
// content here
</div>
)
}
}

How to pass component to onClick in react

import React from 'react'
export default () => {
function clickHandler() {
console.log('Button clicked')
}
return (
<div>
<button onClick={clickHandler}>Click</button>
</div>
)
}
In the above code we see that a function has been passed to the onClick.In the same way to the onClick I need to pass a diffrent component which is present in the same src. This component consists of a .js and a .css file.Could you please help me out with it. Thanks in advance
If you don't mind using classes instead of functions, your other component should look like this:
import React from 'react'
class ShowThisAfterClick extends React.Component {
return (
<div>
<p>This is what you want to show</p>
</div>
)
}
export default ShowThisAfterClick
And now you should update the component you've shown:
import React from 'react'
import ShowThisAfterClick from './where/you/put/the/ShowThisAfterClick.js'
class Main extends React.Component {
constructor(props){
super(props)
this.state = { isButtonClicked: false }
this.clickHandler = this.clickhandler.bind(this)
}
clickHandler() {
this.setState({ isButtonClicked: true })
}
render() {
const { isButtonClicked } = this.state
return (
<div>
<button onClick={ this.clickHandler }>Click</button>
{ isButtonClicked ? <ShowThisAfterClick /> : ''}
</div>
)
}
}
export default Main
If you want to keep using functions, then I would kindly suggest to read the manual, it is more than well written.

react child state doesn't update with props from father (and deeper in the branch)

The problem is following:
I have components: Grandfather, father and child (literally :D).
Grandfather passes his state through props to father (and father sets his state with it).
Then father passes props to child and child also sets state with it.
When i display this.props everything is fine, but when i display
state then i see that nothing has changed in father and child.
I heard there is something like componentWillReceiveProps() but it is already deprecated.
Working example: https://codesandbox.io/s/doesitworkornot-rrcgt?fontsize=14&hidenavigation=1&theme=dark
And codes:
Grandfather.js
import React from "react";
import Father from "./Father";
class GrandFather extends React.Component {
constructor(props) {
super(props);
this.state = {
clickedCounter: 1
};
}
onClick = e => {
this.setState(prevState => ({
clickedCounter: prevState.clickedCounter + 1
}));
};
render() {
return (
<div>
<button onClick={this.onClick}>Press me</button> <br />
Here is Grandfather -> state value={this.state.clickedCounter}
<Father clickedCounter={this.state.clickedCounter} />
</div>
);
}
}
export default GrandFather;
Father.js
import React from "react";
import Child from "./Child";
class Father extends React.Component {
constructor(props) {
super(props);
this.state = {
clickedCounter: this.props.clickedCounter
};
}
render() {
return (
<div>
Here is Father -> props value={this.props.clickedCounter} <br />
Here is Father -> state value={this.state.clickedCounter}
<Child clickedCounter={this.props.clickedCounter} />
</div>
);
}
}
export default Father;
Child.js
import React from "react";
class Child extends React.Component {
constructor(props) {
super(props);
this.state = {
clickedCounter: this.props.clickedCounter
};
}
render() {
return (
<div>
Here is Child -> props value={this.props.clickedCounter} <br />
Here is Child -> state value={this.state.clickedCounter}
</div>
);
}
}
export default Child;
I also heard there is something like cloning children... I'd like to avoid it if possible.
When you initialise state from props, react will not refresh state but it do refresh props. You can use below code to make it work instead of componentWillReceiveProps.
static getDerivedStateFromProps(nextProps) {
return {
clickedCounter: nextProps.clickedCounter,
}
}

React JS - Passing functions for child components

I have an App component and a function 'modalToggled' inside its.
I want to pass the function to multiple child components until I get to the last one, the 'interiores' component.
Like this:
<App> -> <Coluna1> -> <MenuPrincipal> -> <Portfolio> -> <PortfolioMenu> -> <interiores>
App Component, the parent of all components:
import React, { Component } from 'react';
import Coluna1 from './Coluna1'
class App extends Component {
constructor(props) {
super(props)
this.state = {
modalOn: false
}
this.modalToggled = this.modalToggled.bind(this)
}
modalToggled = (on) => {
this.setState({modalOn: on});
}
render() {
return (
<div>
<Coluna1 onModalToggle={this.modalToggled}/>
</div>
)
}
}
export default App;
This is the 'Coluna1' the first child component. I did the same thing in the another ones: 'MenuPrincipal', 'Portfolio', 'PortfolioMenu'
class Coluna1 extends Component {
constructor(props){
super(props)
}
render() {
return (
<div>
<Header />
<MenuPrincipal onModalToggle={this.props.modalToggled} />
</div>
)
}
}
export default Coluna1
Therefore here is the last component interiores, when I click on the button there appears an error message:
TypeError: _this.props.onModalToggle is not a function
import React, { Component } from 'react'
import Modal from 'react-responsive-modal';
class Interiores extends Component {
constructor(props) {
super(props)
this.state = {
open: false
}
}
onOpenModal = () => {
this.setState({ open: true });
this.props.onModalToggle(true);
};
onCloseModal = () => {
this.setState({ open: false });
this.props.onModalToggle(false);
};
render() {
const { open } = this.state;
return (
<div>
<button onClick={this.onOpenModal}>Open modal</button>
<Modal open={open} onClose={this.onCloseModal} center></Modal>
</div>
)
}
}
export default Interiores;
Does anybody know how to solve it? Thank you
It happens, because in App class you pass prop with name onModalToggle:
<Coluna1 onModalToggle={this.modalToggled}/>
But in Coluna1 you receive this props with wrong name, modalToggled:
<MenuPrincipal onModalToggle={this.props.modalToggled} />
Just make the names of props equal. In Coluna1 and other intermediate components pass and receive this props as onModalToggle:
<MenuPrincipal onModalToggle={this.props.onModalToggle} />
This is the problem
modalToggled = (on) => {
this.setState({modalOn: on});
}
Since this is a class function it needs to be defined like
modalToggled(on) {
this.setState({modalOn: on});
}

How to make/access state using props in react?

I made an app with multiple components and want their state to be accessed using parent/main app, I'm not sure how to get it. what i'm trying to do is when i change state in main "App" the component state should change. One of the component is 'checkbox' and now i want to access its state using parent app, I made multiple attempts but not getting it done. my code goes like this..
This is Main 'App' code:
import React, { Component } from 'react';
import Checkbox from './checkbox';
import Radio from './Radio';
import ToggleSwitch from './ToggleSwitch';
import PrimaryButton from './PrimaryButton';
class App extends Component {
onClick(isClicked){
isChecked:true
};
render() {
return (
<div id="form">
<Checkbox
onClick={this.onClick}
/>
<RadioButton
onClick={this.onClick}
/>
</div>
);
}
}
export default App;
The component i want to access goes like this:
import React, { Component } from 'react';
class Checkbox extends Component {
constructor(props){
super(props);
this.state={
isChecked:true
};
};
onCheck(){
this.setState({
isChecked: !this.state.isChecked
});
this.props.isClicked()
};
render() {
return (
<div>
<div
className={this.state.isChecked ? 'checked': 'unchecked'}
onClick={this.onCheck.bind(this)}
>
</div>
</div>
);
}
}
export default Checkbox;
You forgot to bind the onClick event in the app component, try this it will work :
class App extends Component {
onClick(isClicked){
console.log('isClicked', isClicked);
};
render() {
return (
<div id="form">
<Checkbox onClick={this.onClick.bind(this)}/>
</div>
);
}
}
If you already have onClick handler for the Checkbox I don't see why you couldn't just move the state up to the App component and just pass down a callback from there to the Checkbox that will update the parent state. That seems like a more React way to do it, to me.
class App extends Component {
constructor(props){
super(props);
this.state={
isChecked:true
}
}
onClick = (isClicked) => {
this.setState({isChecked: !this.state.isChecked})
}
render() {
return (
<div id="form">
<Checkbox
onClick={this.onClick}
ischecked={this.state.isChecked}
/>
</div>
);
}
}
Component
class Checkbox extends Component {
onCheck(){
this.props.onClick()
}
render() {
return (
<div>
<div
className={this.props.isChecked ? 'checked': 'unchecked'}
onClick={this.onCheck.bind(this)}
>
</div>
</div>
)
}
}

Categories

Resources