react js set state from parent to child component - javascript

So I have a parent and children component.
Parent passes whatever is typed in the search bar as a prop to the children.
then the api fetch should be executed, I see the fetch object in the console. I'm having difficulties setting the children state from the parent.
Any tips would be appreciated, thank you and happing coding :D
class HelloComponent extends React.Component {
render () {
return <h1>Github API repositories </h1>;
}
}
class Parent extends React.Component {
constructor (props) {
super (props);
this.boo = this.boo.bind(this);
this.state = {path: ''};
}
boo = (event) => {
event.preventDefault();
//alert('it works!');
let url = 'https://api.github.com/search/repositories?q='+ this.state.path;
//let parameter = this.state.path;
console.log(url);
I tried using this.props or just this.response..etc
axios.get(url)
.then(response => {
console.log(response.data.items)
this.setState({
repo : this.props.response.data.items
})
})
}
//set the state from the search bar
searchQuery = (event) => {
this.setState({ path : event.target.value });
}
render() {
return(
//call Repositories component and pass the current state as props
<div>
<form onSubmit={this.boo}>
<input type="text" onChange={this.searchQuery} />
<input type="submit" value="Search"/>
</form>
<Child search= {this.state.path} />
{/* <button onClick={this.boo}>fuck</button> */}
</div>
);
}
}
class Child extends React.Component {
constructor (props) {
super (props);
//this.boo = this.boo.bind(this);
this.state = { repo : ''};
}
render () {
{/*
const titles = this.state.repo.map( (repo) =>
<tr key={ repo.id }>
<td> { repo.name }</td>
<td><a href={repo.html_url}>{repo.html_url}</a></td>
</tr>
);
return (
<div>
<table>
<tbody>
<tr><th>Name</th><th>URL</th></tr>
{titles}
</tbody>
</table>
</div>
);
*/}
return (
<h1>{this.state.repo}</h1>
);
}
}
class App extends React.Component {
render () {
return (
<div>
<HelloComponent />
<Parent />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));

I think first is this part of your code is wrong
axios.get(url)
.then(response => {
console.log(response.data.items)
this.setState({
repo : response.data.items
})
})
First you need to pass prop repo to child
<Child repo={this.state.repo} search= {this.state.path} />
To set state of child from parent, you don't need to make any change in parent, Add componentWillReceiveProps method in and setState there
componentWillReceiveProps(nextProps) {
this.setState({
repo: nextProps.repo
})
}

Related

Pass input data from child to parent React.js

This may seem kind of basic but I'm just learning how to use React. Currently what I have going is when I type in the input field and submit, the system console logs my 'search' input. What I'm trying to do is pass my 'search' data from my child component to the parent. Looking for any tips or leads to the right direction.
This is what I have for my child component:
export default class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ''
};
}
onChange = event => {
this.setState({ search: event.target.value });
};
onSubmit = event => {
const { search } = this.state;
event.preventDefault();
console.log(search);
};
render() {
return (
<div className='search-bar'>
<form onSubmit={this.onSubmit}>
<input
className='search'
type='text'
placeholder='Search'
onChange={this.onChange}
search={this.props.search}
value={this.state.searchinput}
parentCallback={this.onChange}
></input>
</form>
<FontAwesomeIcon className='search-icon' icon={faSearch} />
</div>
);
}
}
And in my Parent component (nothing much at the moment)
export default class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ''
};
}
searchUpdate = search => {
console.log(search);
};
render() {
console.log(this.props.search);
return (
<div className='container'>
<SearchBar/>
</div>
);
}
}
Generally to pass data from child component to Parent Component, you can pass a reference of a function as props to child component from parent component and call that passed function from child component with data.
You can do something like this:
export default class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ''
};
}
onChange = event => {
this.setState({ search: event.target.value });
};
onSubmit = event => {
const { search } = this.state;
event.preventDefault();
console.log(search);
this.props.passSearchData(search);
};
render() {
return (
<div className='search-bar'>
<form onSubmit={this.onSubmit}>
<input
className='search'
type='text'
placeholder='Search'
onChange={this.onChange}
search={this.props.search}
value={this.state.searchinput}
parentCallback={this.onChange}
></input>
</form>
<FontAwesomeIcon className='search-icon' icon={faSearch} />
</div>
);
}
In parent component:
export default class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ''
};
}
searchUpdate = search => {
console.log(search);
this.setState({ ...state, search: search })
};
render() {
console.log(this.props.search);
return (
<div className='container'>
<SearchBar passSearchData={this.searchUpdate} />
</div>
);
}
The simplest way would be to pass a function from parent to child:
// in parent component
const setSearchValue = (search) => {
// setState to search
this.setState({search});
}
render (){
return <>
<SearchBar onsearch={this.setSearchValue} />
</>
}
// in child component
// change your searchUpdate
searchUpdate = () => {
const {onsearch} = this.state;
// function call to pass data to parent
this.props.onsearch(onsearch)
}
Just have a function that is passed as a prop to the child component. Let child component do the handle change part and pass the value back to the parent and then do whatever you want to with the value
Code sandbox: https://codesandbox.io/s/react-basic-example-vj3vl
Parent
import React from "react";
import Search from "./Search";
export default class Parent extends React.Component {
searchUpdate = search => {
console.log("in parent", search);
};
render() {
console.log(this.props.search);
return (
<div className="container">
<Search handleSearch={this.searchUpdate} />
</div>
);
}
}
Child
import React from "react";
export default class Search extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ""
};
}
onChange = event => {
this.setState({ search: event.target.value }, () => {
console.log("in child", this.state.search);
this.props.handleSearch(this.state.search);
});
};
onSubmit = event => {
const { search } = this.state;
event.preventDefault();
console.log(search);
};
render() {
return (
<div className="search-bar">
<form onSubmit={this.onSubmit}>
<input
className="search"
type="text"
placeholder="Search"
onChange={this.onChange}
search={this.props.search}
value={this.state.searchinput}
/>
</form>
</div>
);
}
}

Child React Component Will Not show on state change

I am having an issue getting a third component to show up using REACT.
I am trying to change the state of workflow, and show Component Three, but I am not sure what I am doing wrong.
After clicking on the continue button, the state changes.
Workflow is changed to WELCOME_MSG, the switch below works.
But I can't seem to return this Component "ComponentThree"
case 'WELCOME_MSG':
return ();
class ComponentOne extends React.Component {
constructor(props) {
super(props)
this.state = {
workflow: 'GET_NAME'
}
this.setWorkflow = this.setWorkflow.bind(this);
}
setWorkflow() {
switch(this.state.workflow){
case 'GET_NAME':
return (<ComponentTwo/>);
case 'WELCOME_MSG':
return (<ComponentThree name={this.state.name} />);
}
}
render() {
console.log('ComponentOne: ',this.state.workflow );
return this.setWorkflow();
/*
switch(this.state.workflow){
case 'GET_NAME':
return (<ComponentTwo/>);
case 'WELCOME_MSG':
return (<ComponentThree name={this.state.name} />);
} */
}
}
// showThree()
class ComponentTwo extends React.Component {
constructor(props){
super(props)
this.state = {
workflow: 'GET_NAME',
name: 'Chris'
}
this.handleChange = this.handleChange.bind(this);
this.handleClick = this.handleClick.bind(this);
this.setWorkflow = this.setWorkflow.bind(this);
}
handleChange(e) {
//this.setState({name: event.target.name});
e.persist();
console.log('handleChange event.target.name:', e.target);
this.setState((prevState, props) => {
return {
name: e.target.value,
workflow: 'WELCOME_MSG',
}
})
/*
this.setState(state => ({
//name: this.state.name,
name: e.target.value,
//name: "sadfasdf",
})); */
}
setWorkflow() {
console.log("setWorkflow", this.state.workflow);
switch(this.state.workflow){
case 'GET_NAME':
return (<ComponentTwo/>);
case 'WELCOME_MSG':
return (<ComponentThree />);
}
// name={this.state.name}
}
handleClick(e) {
//console.log(this.state);
//e.preventDefault();
console.log('BEFORE handleClick this STATE ON CLICK :', this.state.workflow);
console.log('this.state.name:', this.state.name);
this.setState((prevState, props) => {
return {
workflow: 'WELCOME_MSG',
name: this.state.name,
}
})
return this.setWorkflow();
//this.setWorkflow = this.setWorkflow.bind(this);
/* this.setState(state => ({
//name: this.state.name,
name: this.state.name,
workflow: 'WELCOME_MSG'
})); */
console.log('ON CLICK AFTER SET STATE:', this.state);
//return (<ComponentThree name={this.state.name} />);
// e.preventDefault();
}
render() {
//console.log('this is:', this);
// onChange={this.handleChange}
return (
<div>
<h1>Enter your name</h1>
<div className="grid20 md-grid100">
<input type="text" name="fname" value={this.state.name} onChange={this.handleChange} />
</div>
<div className="grid80 md-grid100">
<button onClick={this.handleClick} >Continue</button>
</div>
</div>
)
}
}
class ComponentThree extends React.Component {
render() {
console.log('ComponentThree this is:', this);
return (
<div className="test">
<h1>Hello {this.state.name}</h1>
<h2>sfasfdadf</h2>
</div>
)
}
}
ReactDOM.render(<ComponentOne />, document.querySelector("#app"))
JS Fiddle Below
https://jsfiddle.net/ameshkin/cvg2rjzo/32/
The state variable to show ComponentTwo or Three is in ComponentOne, but you are updating the state in ComponentTwo, and not updating the state in ComponentOne. To update the state in ComponentOne, you need to pass a function from One to Two in the props.
Edit:
Here's a working fiddle https://jsfiddle.net/j5gxovdm/
Basically having the state in one place, instead of spread across all components (keeping a single source of truth)
return (
this.state.workflow == 'GET_NAME'
? <ComponentTwo
setWorkflow={this.setWorkflow.bind(this)}
onChange={(e) => this.setState({name: e.target.value})}
name={this.state.name}
/>
: <ComponentThree name={this.state.name} />
)
ComponentTwo has its own state and that state is updated upon clicking the button, not the ComponentOne state. As ComponentOne is a container component to switch ComponentTwo and ComponentThree, you have to pass the ComponentOne state as props for ComponentTwo and ComponentThree.
JS Fiddle Below
https://jsfiddle.net/richard929/g0b4d3ur/1/

React: Remove current instance of component [duplicate]

I have have code that creates <li> elements. I need to delete elements one by one by clicking. For each element I have Delete button. I understand that I need some function to delete items by id. How to do this function to delete elements in ReactJS?
My code:
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {items: [], text: ''};
}
render() {
return (
<div>
<h3>TODO</h3>
<TodoList items={this.state.items} />
<form onSubmit={this.handleSubmit}>
<input onChange={this.handleChange} value={this.state.text} />
<button>{'Add #' + (this.state.items.length + 1)}</button>
</form>
</div>
);
}
handleChange(e) {
this.setState({text: e.target.value});
}
handleSubmit(e) {
e.preventDefault();
var newItem = {
text: this.props.w +''+this.props.t,
id: Date.now()
};
this.setState((prevState) => ({
items: prevState.items.concat(newItem),
text: ''
}));
}
delete(id){ // How that function knows id of item that need to delete and how to delete item?
this.setState(this.item.id)
}
}
class TodoList extends React.Component {
render() {
return (
<ul>
{this.props.items.map(item => (
<li key={item.id}>{item.text}<button onClick={this.delete.bind(this)}>Delete</button></li>
))}
</ul>
);
}
}
You are managing the data in Parent component and rendering the UI in Child component, so to delete item from child component you need to pass a function along with data, call that function from child and pass any unique identifier of list item, inside parent component delete the item using that unique identifier.
Step1: Pass a function from parent component along with data, like this:
<TodoList items={this.state.items} _handleDelete={this.delete.bind(this)}/>
Step2: Define delete function in parent component like this:
delete(id){
this.setState(prevState => ({
data: prevState.data.filter(el => el != id )
}));
}
Step3: Call that function from child component using this.props._handleDelete():
class TodoList extends React.Component {
_handleDelete(id){
this.props._handleDelete(id);
}
render() {
return (
<ul>
{this.props.items.map(item => (
<li key={item.id}>{item.text}<button onClick={this._handleDelete.bind(this, item.id)}>Delete</button></li>
))}
</ul>
);
}
}
Check this working example:
class App extends React.Component{
constructor(){
super();
this.state = {
data: [1,2,3,4,5]
}
this.delete = this.delete.bind(this);
}
delete(id){
this.setState(prevState => ({
data: prevState.data.filter(el => el != id )
}));
}
render(){
return(
<Child delete={this.delete} data={this.state.data}/>
);
}
}
class Child extends React.Component{
delete(id){
this.props.delete(id);
}
render(){
return(
<div>
{
this.props.data.map(el=>
<p onClick={this.delete.bind(this, el)}>{el}</p>
)
}
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'))
<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>
<div id='app'/>

How to pass a prop to a component that is returned based on state?

I am attempting to return a component based on a parameter that was passed on a onClick handler this.showComponentToRender('features'). If features is clicked, it runs the showComponentToRender(name) and sets the state and in the render(), the {this.state.showComponent} shows the proper component.
However, a problem surfaces when I attempt to pass a prop resetFeatures={this.props.resetFeatures} within the
showFeatures() {
return (<FeaturesList
updateCad={this.props.updateCad}
resetFeatures={this.props.resetFeatures}
/>);
}
Clicking on the RESET A4 link, calls the resetCrossbow() which activates a function in the parent component. The parent component updates its state, and passes the state as a prop to its child.
For some reason, I can not get the resetFeatures prop to come into the <FeaturesList /> component if I return it within a function that gets set in state. Why is this? I am looking for suggestions to fix.
If I do the traditional method of placing the <FeaturesList /> within the return of the render(), all is well.
Here's the component
import React, { Component } from 'react';
import FeaturesList from './FeaturesList';
import ColorsList from './ColorsList';
import './../assets/css/features-menu.css';
export default class FeaturesMenu extends Component {
constructor(props) {
super(props);
this.state = {
showComponent: this.showFeatures()
};
this.showFeatures = this.showFeatures.bind(this);
this.showColors = this.showColors.bind(this);
}
showFeatures() {
return (<FeaturesList
updateCad={this.props.updateCad}
resetFeatures={this.props.resetFeatures}
/>);
}
showColors() {
this.props.resetCrossbow();
return <ColorsList switchColor={this.props.switchColor} />
}
showComponentToRender(name) {
if (name === 'features') {
this.setState({
showComponent: this.showFeatures()
});
} else {
this.setState({
showComponent: this.showColors()
})
}
}
render() {
// console.log(`this.props.resetFeatures: ${this.props.resetFeatures}`);
return (
<div id="features-menu-wrapper">
<nav id="features-menu">
<li onClick={() => this.showComponentToRender('features')}>FEATURES</li>
<li onClick={() => this.showComponentToRender('colors')}>COLORS</li>
<li onClick={() => this.props.resetCrossbow()}>RESET A4</li>
</nav>
<div id="component-wrapper">
{this.state.showComponent} // <- I am not able to pass resetFeatures prop if I do it this way. Why?
{/* <FeaturesList
updateCad={this.props.updateCad}
resetFeatures={this.props.resetFeatures} <- I am able to pass resetFeatures prop as normal.
/>
<ColorsList switchColor={this.props.switchColor} /> */}
</div>
</div>
);
}
}
The easiest way to achieve results is pass additional properties to render specific components function and use spread to pass these props to the rendered component:
const FeaturesList = ({additional = 'Empty'} = {}) => <div>Feature List with additional prop <b>{additional}</b></div>
const ColorsList = ({additional = 'Empty'} = {}) => <div>Colors List with additional prop <b>{additional}</b></div>
class FeaturesMenu extends React.Component {
constructor(props) {
super(props);
this.state = {
showComponent: this.showFeatures({additional: 'Initial features'})
};
this.showFeatures = this.showFeatures.bind(this);
this.showColors = this.showColors.bind(this);
}
showFeatures(props) {
return (<FeaturesList
updateCad={this.props.updateCad}
resetFeatures={this.props.resetFeatures}
{...props}
/>);
}
showColors(props) {
this.props.resetCrossbow();
return <ColorsList switchColor={this.props.switchColor} {...props} />
}
showComponentToRender(name) {
if (name === 'features') {
this.setState({
showComponent: this.showFeatures({additional: 'features adds'})
});
} else {
this.setState({
showComponent: this.showColors({additional: 'colors adds'})
})
}
}
render() {
return (
<div id="features-menu-wrapper">
<nav id="features-menu">
<li onClick={() => this.showComponentToRender('features')}>FEATURES</li>
<li onClick={() => this.showComponentToRender('colors')}>COLORS</li>
<li onClick={() => this.props.resetCrossbow()}>RESET A4</li>
</nav>
<div id="component-wrapper">
{this.state.showComponent}
</div>
</div>
);
}
}
const props = {
resetCrossbow: () => null,
switchColor: () => null,
updateCad: () => null,
resetFeatures: () => null
}
ReactDOM.render(<FeaturesMenu {...props}/>, document.querySelector('root'))
<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>
<root/>
You should not save the entire component in your state. Just set a string related to it and as the value changes, the FeaturesMenu will react and
call the function to render the correct component. Obviously, this code can be changed, but I think I've made my point. =)
const FeaturesList = props => (<div>Features List</div>);
const ColorsList = props => (<div>Colors List</div>);
class FeaturesMenu extends React.Component {
constructor(props) {
super(props);
this.state = {
currentComponent: 'Features'
};
this.showFeatures = this.showFeatures.bind(this);
this.showColors = this.showColors.bind(this);
}
showFeatures() {
return (<FeaturesList
updateCad={this.props.updateCad}
resetFeatures={this.props.resetFeatures}
/>);
}
showColors() {
this.props.resetCrossbow();
return <ColorsList switchColor={this.props.switchColor} />
}
showComponentToRender(name) {
this.setState({ currentComponent: name })
}
render() {
return (
<div id="features-menu-wrapper">
<nav id="features-menu">
<li onClick={() => this.showComponentToRender('Features')}>FEATURES</li>
<li onClick={() => this.showComponentToRender('Colors')}>COLORS</li>
<li onClick={() => this.props.resetCrossbow()}>RESET A4</li>
</nav>
<div id="component-wrapper">
{this[`show${this.state.currentComponent}`]()}
</div>
</div>
);
}
}
// for testing purposes
const props = {
resetCrossbow: () => {},
switchColor: () => {},
updateCad: () => {},
resetFeatures: () => {}
}
ReactDOM.render(<FeaturesMenu {...props}/>, document.querySelector('main'))
<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>
<main/>

Is this how one passes a method of a Parent component to a child in React?

In a section of a book I am coding along with it explains how a child component would get access to a parents methods.
The way to communicate from the child to a parent is by passing callbacks from the parent to the child, which it can call to achieve specific tasks. In this case, you pass createIssue as a callback property from IssueTable to IssueAdd. From the child, you just call the passed in function in your handler to create a new issue.
The author mentions IssueTable (sibling) to IssueAdd(sibling) he probably meant IssueList (parent) to IssueAdd(child)—right?
I would think just by examining the return JSX from IssueList...
We could see IssueTable is sibling to IssueAdd, no?
const contentNode = document.getElementById('contents');
class IssueFilter extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
This is placeholder for the Issue Filter.{this.props.name}
{this.props.age}
</div>
);
}
}
const IssueRow = props => (
<tr>
<td>{props.issue.id}</td>
<td>{props.issue.status}</td>
<td>{props.issue.owner}</td>
<td>{props.issue.created.toDateString()}</td>
<td>{props.issue.effort}</td>
<td>{props.issue.completionDate ? props.issue.completionDate.toDateString() : ''}</td>
<td>{props.issue.title}</td>
</tr>
);
function IssueTable(props) {
const issueRows = props.issues.map(issue => <IssueRow key={issue.id} issue={issue} />);
return (
<table className="bordered-table">
<thead>
<tr>
<th>Id</th>
<th>Status</th>
<th>Owner</th>
<th>Created</th>
<th>Effort</th>
<th>Completion Date</th>
<th>Title</th>
</tr>
</thead>
<tbody>{issueRows}</tbody>
</table>
);
}
class IssueAdd extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
var form = document.forms.issueAdd;
console.log('form', document.forms);
this.props.createIssue({
owner: form.owner.value,
title: form.title.value,
status: 'New',
created: new Date()
});
//clear the form for the next input
form.owner.value = '';
form.title.value = '';
}
render() {
return (
<div>
<form name="issueAdd" onSubmit={this.handleSubmit}>
<input type="text" name="owner" placeholder="Owner" />
<input type="text" name="title" placeholder="Title" />
<button>Add</button>
</form>
</div>
);
}
}
class IssueList extends React.Component {
constructor(props) {
super(props);
this.state = { issues: [] };
this.createIssue = this.createIssue.bind(this);
}
componentDidMount() {
this.loadData();
}
loadData() {
fetch('/api/issues')
.then(response => response.json())
.then(data => {
console.log('Total count of records:', data._metadata.total_count);
data.records.forEach(issue => {
issue.created = new Date(issue.created);
if (issue.completionDate) issue.completionDate = new Date(issue.completionDate);
});
this.setState({ issues: data.records });
})
.catch(err => {
console.log(err);
});
}
createIssue(newIssue) {
fetch('/api/issues', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newIssue)
})
.then(response => {
if (response.ok) {
response.json().then(updatedIssue => {
updatedIssue.created = new Date(updatedIssue.created);
if (updatedIssue.completionDate) updatedIssue.completionDate = new Date(updatedIssue.completionDate);
const newIssues = this.state.issues.concat(updatedIssue);
this.setState({ issues: newIssues });
}); //**/
} else {
response.json().then(error => {
alert('Failed to add issue: ' + error.message);
});
}
})
.catch(err => {
alert('Error in sending data to server: ' + err.message);
});
}
render() {
return (
<div>
<h1>Issue Tracker</h1>
<IssueFilter />
<hr />
<IssueTable issues={this.state.issues} />
<hr />
<IssueAdd createIssue={this.createIssue} />
</div>
);
}
}
ReactDOM.render(<IssueList />, contentNode);
So in short all one has to do to leverage a function declared in a parent is the following....?
const contentNode = document.getElementById('contents');
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.props.someFunc; //So naming this prop someFunc will just help us identify this prop should get the function from the parent?
}
}
class Parent extends React.component{
constructor(props) {
super(props);
this.someFunc = this.someFunc.bind(this);
}
someFunc(){
....
}
render() {
return (
<div>
<ChildComponent someFunc={this.someFunc} /> // Parent's someFunc gets passed as a value to the ChildComponent's prop which is someFunc?
</div>
);
}
}
ReactDOM.render(<Parent />, contentNode);
Yes IssueTable and IssueAdd are in fact siblings from the code snippet you posted.
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.props.someFunc; //So naming this prop someFunc will just help us identify this prop should get the function from the parent?
}
}
In the above snippet this.props.someFunc will not serve any purpose, it will just return the function which you sent from ParentComponent but nothing will happen.
If you are planning to modify or change parent's state from an action in the ChildComponent then the below snippet might make more sense.
class ChildComponent extends React.Component {
constructor(props) {
super(props);
}
handleOnClick = (event) => {
// The name is someFunc because that is what you sent as props from the
// ParentComponent <ChildComponent someFunc={this.someFunc} />
// If it had been <ChildComponent callbackToParent={this.someFunc} />
// then you should access the function as this.props.callbackToParent
// and invoke as this.props.callbackToParent()
this.props.someFunc();
}
render() {
return (
<div onClick={this.handleOnClick}>
Click to trigger callback sent by parent
</div>
)
}
}

Categories

Resources