reactjs Onclick event ,sending value to parent - reactjs

I'm fairly very new to ReactJS, JavaScript and whole coding thing.
I have made a list of array that is being passed on to child from parent component, now I want to make a onClick event that whenever user click on any of that list item.
The value (used as key id) is sent back to the parent, so the parent can send that key value to another child which will use conditional rendering based on that key to which component to render. I preferably don't want to use any other library like flux.
I am stuck as I can;t pass that value from child back to parent. There is some confusion about syntax I think or maybe my logic is not correct. I have only able to bind it to a function within the child class to check if the click is being registered.
class Parent extends React.Component {
render() {
var rows = [];
this.props.listlinkarray.forEach(function(linklist) {
rows.push(<Child linklist={linklist} key={linklist.key} />);
});
return (
<div>
<h3> ListHead </h3>
{rows}
</div>
);
}}
class Child extends React.Component {
// was checking how the Onclick event works //
getComponent(data,event) {
console.log('li item clicked!');
console.log(data);
event.currentTarget.style.backgroundColor = '#ccc';
}
render() {
return (
<div>
<ul><li onClick={this.getComponent.bind(this,this.props.linklist.key)}>
</div>
);
}
}
Array has this data
var ListNameAndLinks= [
{ name:'ABC', key:1} ,
{ name:'BCD', key:2}
];
I want to pass the value the parent get from child based on click to this class so it can render based on that value it get.
class Check extends React.Component {
render() {
var i = 1
// i want that value from parent to this component in if condition
if (i=1) {
return <UIone />;
}
return <UItwo />;
}
}

Pass a onClick method from parent component, like this:
this.props.listlinkarray.forEach((linklist)=>{
rows.push(<Child linklist={linklist} key={linklist.key} onClick={this.onClick.bind(this)}/>);
});
Define this function in Parent:
onClick(key){
console.log(key);
}
In Child Component call this method and pass the id back to parent, like this:
getComponent(key) {
this.props.onClick(key);
}
It will work.
Check the jsfiddle for working example: https://jsfiddle.net/ahdqq5yy/

Related

How do I implement an onClick method in one child component that updates the text in a sibling component, based on the state in App.js?

Every row in my SideMenuContainer corresponds to an object from schema.json, showing only the name property. The behavior I want is that when a row is clicked, the PaneViewContainer toggles to display the name and other properties of that respective object from the json.
In App.js, the data is passed to SideMenuContainer like so:
render() {
return (
<MainContainer>
<SideMenuContainer genInfoList={this.state.genInfoList}/>
<PaneViewContainer genInfoList={this.state.genInfoList}/>
</MainContainer>
);
}
In SideMenuContainer, every row is populated like this:
render() {
return (
<SideMenuPane>
<SideMenu>
<div>
<h2>GenInfo</h2>
{this.props.genInfoList.map(genInfoElement => {
return (
<SideMenuRow>
{genInfoElement.name}
</SideMenuRow>
);
})}
</div>
</SideMenu>
</SideMenuPane>
);
}
What I want to do is change the genInfoList information being displayed in the PaneViewContainer based on which row is clicked in its sibling, SideMenuContainer.
The entire genInfoList data is being passed to both sibling components from their parent App.js, so I want to change which portion of that data is loaded in the Pane based on the row clicked in the SideMenu.
I thought about using the Context API, but I'm having trouble figuring out how to implement it for this purpose. Any ideas?
If I understand correctly you have your information stored in the parent element of both components then you can just pass a function down as a prop and have all of your logic stored in the parent element.
changeInfoList = id => {
//change your info list based on id or index or whatever
this.setState({
//your new list
})
}
render() {
return (
<MainContainer>
<SideMenuContainer changeInfoList={this.changeInfoList} genInfoList={this.state.genInfoList}/>
<PaneViewContainer genInfoList={this.state.genInfoList}/>
</MainContainer>
);
}
and then call changeInfoList from your component with props
render() {
return (
<SideMenuPane>
<SideMenu>
<div>
<h2>GenInfo</h2>
{this.props.genInfoList.map(genInfoElement => {
return (
<SideMenuRow>
{genInfoElement.name}
<button onClick={this.props.changeInfoList(genInfoElement.id)>CLick Me</button>
</SideMenuRow>
);
})}
</div>
</SideMenu>
</SideMenuPane>
);
}
this is commonplace in react as you should have smart components and dumb components. When you have components not in the same tree or spread far away then the context api is very useful. In your case I don't think its necessary.
Without external state management, you would have to pass down a callback (as props), so the children can update the parent's state.
As the components get far away from each other, this pattern can get annoying (passing down callbacks each time). That's where external state management can help.
Here's a simple (and untested) example using a callback:
class Counter extends React.Component {
constructor() {
super();
this.increment = this.increment.bind(this);
this.state = {count: 0};
}
increment() {
let count = thist.state.count;
this.setState({count: count + 1});
}
render() {
return <div>
<CounterButton increment={this.increment}/>
<CounterDisplay count={this.state.count}/>
</div>;
}
}
class CounterButton extends React.Component {
render() {
let increment = this.props.increment;
return <button onClick={increment}>Plus One</button>;
}
}
class CounterDisplay extends React.Component {
render() {
let count = this.props.count;
return <span>{count}</span>;
}
}

Reactjs coding with parent and child component

I have 3 components, that is 2 child components and one parent component.
I wanted to pass the child component value to parent (only the values not the components enitirely,it should not visible in parent) and this values from parent to another child component.
Any suggestions or logic of how to proceed on this, since I don't have any guidance as of right now I had to ask here. Is the above problem possible.
The code is very complex, so I have not put here.
Thank you
When you say values, do you mean state, props, user input, something else?
If you mean state or props: React has a 1-way data flow, so the easiest way to accomplish this is to actually store the data at a higher level. Either store the data used by the child in the parent and pass it down to the children for consumption, or else use a store that both parent and children have access to. Either way, this will make it much easier for all components to access the data.
If you mean user input: one way you can accomplish this is to pass a callback from the parent component to the child as a prop, and then in the child call that callback when a user does something or changes some value. The callback function can make the data accessible to the parent on that user action, and then you can decide what to do with the data from there.
AksharaDL,
Child to Parent — Use a callback and states
Parent to Child — Use Prop
Also here is another article explaining it: https://medium.com/#ruthmpardee/passing-data-between-react-components-103ad82ebd17
here is the solution.
in parrent component you have a state. and have a setData method to update state. pass setData to ChildOne use props. and data to ChilTwo and use it
class StoreBanner extends React.Component {
constructor() {
this.state = {
data: 'whatever'
}
}
setData = (data) => {
this.setState({data})
}
render() {
return (
<div>
<ChildOne setData={this.setData}/>
<ChildTwo data={this.state.data}/>
</div>
)
}
}
and in ChildOne you can update the parrent state
class ChildOne extends React.Component {
setParentData = () => {
this.props.setData('another')
}
...
}
You can do it like this.
class ParentComp extends React.Component {
constructor() {
super();
this.state = {
theStateToPass: null
}
this.receiveDataFromChild = this.receiveDataFromChild.bind(this);
}
receiveDataFromChild(data) {
this.setState({
theStateToPass: data
})
}
render() {
return (
<div>
<FirstChild updateMe={this.receiveDataFromChild} />
<SecondChild stateFromFirstChild={this.state.theStateToPass} />
</div>
)
}
}
class FirstChild extends React.Component {
constructor(props) {
super(props);
this.callParentMethod = this.callParentMethod.bind(this);
}
callParentMethod(e) {
let someDataToSend = "ABC";
this.props.updateMe(someDataToSend)
}
render() {
return (
<div onClick={this.callParentMethod}>
</div>
)
}
}
class SecondChild extends React.Component {
render() {
return (
<div>
{this.props.stateFromFirstChild}
</div>
)
}
}
however it becomes complex and might lead to one's pulling their hair out. so i would suggest using redux , it keeps the flow simple , you have a reducer , actions and a container. everything goes with a flow and keeps it clean but it does comes with an extra overhead of more code as you will be creating container reducer and actions.

Call a child component function from parent class in react.js [duplicate]

I have simple component called List which is a simple ul with some li inside. Each li is a simple component.
I have other parent component which render one input field and the List component. Tapping on Send key I catch text of input field. I want to call for example a function called handleNewText(inputText) but this function need to stay inside List component because the state I use to populate other li components live in List component.
I don' t want to refactor List and MyParent component passing the manage of data from List to MyParent.
first is parent and second is child
class TodoComp extends React.Component {
constructor(props){
super(props);
this.handleKeyPress = this.handleKeyPress.bind(this);
}
componentDidMpunt(){
console.log(this._child.someMethod());
}
handleKeyPress(event){
if(event.key === 'Enter'){
var t = event.target.value;
}
}
render(){
return (
<div>
<input
className="inputTodo"
type="text"
placeholder="want to be an hero...!"
onKeyPress={this.handleKeyPress}
/>
<List/>
</div>
);
}
}
export default class List extends React.Component {
constructor() {
super();
this.flipDone = this.flipDone.bind(this);
this.state = {
todos: Array(3).fill({ content: '', done: false})
};
}
flipDone(id) {
let index = Number(id);
this.setState({
todos: [
...this.state.todos.slice(0, index),
Object.assign({}, this.state.todos[index], {done: !this.state.todos[index].done}),
...this.state.todos.slice(index + 1)
]
});
}
render() {
const myList = this.state.todos.map((todo, index) => {
return (
<Todo key={index}
clickHandler={this.flipDone}
id={index}
todo={todo}
handleText={this.handleText}
/>
);
})
return (
<ul className="list">
{myList}
</ul>
);
}
ReactDOM.render(<TodoComp />,document.getElementById('myList'));
You need to make use of refs to call a function in the child component from the parent component
render the List component from parent as
<List ref="myList"/>
and then access the handleNewText() function as this.refs.myList.handleNewText()
UPDATE:
Strings refs are no longer recommended by React, you should rather use ref callbacks, check this
<List ref={(ref) => this.myList=ref}/>
and then access the child function like
this.myList.handleNewText()
Adding to #shubham-khatri solution:
If you are referencing a connected child component...
a. That child must say withRef: true in the (4th) config parameter:
#connect(store => ({
foo: store.whatever
…
}),null,null,{ withRef: true })
b. Access is through getWrappedInstance() (note, that getWrappedInstance also needs to be called ())
getWrappedInstance().howdyPartner()
I started learning React when functional component came out. Another way I experimented with some success is returning functions that you want to access as closures within a JSON. I like this method because closure is a construct of Javascript and it should still work even if React is updated yet again. Below is an example of child component
function Child(){
//declare your states and use effects
const [ppp, setPPP] = useState([]);
const [qqq, setQQQ] = useState(2);
//declare function that you want to access
function funcA(){ /*function to interact with your child components*/}
function funcB(){ /*function to interact with your child components*/}
//pure React functional components here
function Content(){
//function that you cannot access
funcC(){ /*.....*/}
funcD(){/*.......*/}
//what to render
return (
<div>
{/* your contents here */}
</div>
)
}
//return accessible contents and functions in a JSON
return {
content: Content, //function for rendering content
ExposeA: funcA, //return as a closure
ExposeB: funcB, //return as a closure
}
}
Below is an example of how you would render the child contents within the parent
function Parent(){
let chi = Child();
let ChildContent = chi.Content;
//calling your exposed functions
//these function can interacts with the states that affects child components
chi.ExposeA();
chi.ExposeB();
//render your child component
return (<div>
<div> {/* parent stuff here */</div>
<div> {/* parent stuff here */</div>
<ChildContent {/*Define your props here */} />
</div>)
}

ReactJS: Parent child partial update

I'm having a bit of a trouble getting my head around how i would communicate between my parent and child components in my specific use case.
I have a child component that renders some points using an external lib.
What I'm currently doing is implementing componentDidMount/Update and use the external lib to render the points in this.props.points (which is an array provided by the parent component).
Rendering the points involves looping through them and call something like ExternalLib.addPoint(point).
What i would like to do, instead of looping through all the points everytime this.props.points changes, is making the parent component add (or remove) individual points to the child component.
Is it React friendly to call something like this.refs.myChild.addPoint(point) in the parent component?
Are there other techniques to achieve something like this?
Update
Here's some code (https://jsfiddle.net/69z2wepo/61366/):
const ExternalLib = {
addPoint: function(el, point) {
var li = document.createElement("li");
li.innerHTML = point;
el.appendChild(li);
}
}
class Child extends React.Component {
componentDidMount() {
this.renderPoints();
}
componentDidUpdate() {
this.renderPoints();
}
renderPoints() {
const el = this.refs.points;
el.innerHTML = '';
this.props.points.forEach(function(point) {
ExternalLib.addPoint(el, point);
});
}
render() {
console.log('render')
return (
<div>
<ul ref="points"></ul>
</div>
);
}
}
class Parent extends React.Component {
constructor() {
super();
this.state = {
points: []
};
}
addPoint() {
const points = this.state.points.slice();
points.push((new Date()).getTime());
this.setState({
points: points
});
}
render() {
return (
<div>
<button onClick={this.addPoint.bind(this)}>Add Point</button>
<Child points={this.state.points} />
</div>
);
}
}
ReactDOM.render(
<Parent />,
document.getElementById('container')
);
This is simplified because in this example I could generate the markup directly making use of map and leveraging React's partial DOM update - the external lib does some extra stuff that's not in this question's scope.
Thanks!
If you want to interfere with React rendering process, you can code shouldcomponentupdate.
In your children, if you make shouldcomponentupdate return false and call ExternalLib.addPoint(point), it should do the job:
shouldComponentUpdate(nextProps){
//comparePoints() is a function able to find if a new point is present in the list, comparing existing used points with new one
var newPoint = comparePoints(this.props.points, nextProps.points)
if(newPoint){
ExternalLib.addPoint(newPoint);
//forbide re-render
return false;
}
//enable other update
return true;
}

React — onScroll listener for parent element?

How can I add an onScroll listener in a component to catch a scroll of a parent element?
class ChildDiv extends React.Component {
constructor() {
super();
}
handleScrollOfParent() {
// do stuff when parent <main> scrolls;
}
render() {
return (
<div id="child" onScroll={this.handleScrollOfParent.bind(this)}>
// content with overflow: hidden and scroll handled by parent MAIN.
</div>
)
}
}
export default ChildDiv;
Rendered in a parent main, like this <main><ChildDiv /></main> and I want to catch the scroll of the main.
You could either:
1) try to grab the parent node from the child component:
componentDidMount() {
ReactDOM.findDOMNode(this).parentNode.addEventListener(...
}
2) pass the parent node as props and attach listener after rendered:
In parent:
render{
return(
<div className="parent" ref={(elem)=>{this.node=elem}}>
<Child parentNode={this.node}/>
</div>
)
}
and in child (parentNode is still undefined in constructor, check in next props):
componentWillReceiveProps(newProps){
newProps.parentNode.addEventListener(...
}
According to React's nature, which is passing props from Parent down to Children, so when you want the Child element to update its parent, you need to create a function on Parent, and pass to the Child as props
Please also refer to my answer to a similar issue (how to trigger the parent component to do something from the child/grandchild/or great-grandchild):
Re-initializing class on redirect
In your case, we may do something like this:
1/ Create a function on Parent that trigger the Parent itself to do something:
import React from 'react';
class Parent extends React.Component {
constructor(props) {
super(props);
// ...
}
doSomeThingOnParent = () => {
// do whatever you want with this Parent component, setState, forceUpdate etc.
}
render(){
// ...
<Child doSomeThingOnParent={this.doSomeThingOnParent} />
// ...
}
}
2/ On Child Component, trigger the above function using onScroll:
class Child extends React.Component {
...
render() {
return (
<div id="child" onScroll={this.props.doSomeThingOnParent}>
// your content
</div>
)
}
}
However, you cannot render the Parent by your mentioned way, which is:
You should use like the Parent's render method above, and also set the CSS to allow overflow for your Child component
You could define a state variable in the parent component that would store the current scrollTop value (assuming vertical scrolling) and update in every time the scroll event happens and then pass this variable to the ChildDiv which could detect that the variable has changed in componentWillReceiveProps:
if(this.props.yourVariable != nextProps.yourVariable){
// scroll event was fired => scroll position changed
}

Resources