Sending onMouseDown from parent to child - reactjs

Is there a way to send the clickevent from the parent to the child?
This is my parent component:
<Component {...props}>
<Child />
{props.children}
</Component>
This is the child component:
<Component onMouseDown={e => this.handleClick(e, props)}></Component>
Whenever the parent component is clicked I want to trigger the handleclick component of my child.
Thanks in advance!

You can use a reference to your child component:
// parent.js
constructor(props) {
super(props);
this.child = React.createRef();
}
handleMouseDown = e => {
this.child.current.handleClick(e, this.props);
}
render() {
return (
<Component onMouseDown={this.handleMouseDown} {...props}>
<Child ref={this.child}/>
{props.children}
</Component>
)
}

You can do this using rxjs with Observable and Subscriptions. Here is a working example and I'll explain what's going on https://codesandbox.io/s/7wjwnznk3j
Relevant reading:
fromEvent: https://rxjs-dev.firebaseapp.com/api/index/function/fromEvent
subscription: https://rxjs-dev.firebaseapp.com/api/index/class/Subscription
I used Typescript since I prefer it, but is absolutely not a requirement. You parent class will look like this:
interface State {
obs$?: Observable;
}
class App extends React.Component<null, State> {
public readonly state: State = {};
public ref: React.Ref<React.ReactHTMLElement>;
componentDidMount() {
this.setState({
obs$: fromEvent(this.ref, 'click')
});
}
#Bind()
setParentRef(el: HTMLElement) {
this.ref = el;
}
render() {
return (
<div style={parentStyles} ref={this.setParentRef}>
<Child parentClick={this.state.obs$} />
</div>
);
}
}
We have our ref this.ref and set it through the function, we need this since it is the target of a fromEvent and click is the event. This automatically creates an observable that will emit to any subscribers when it is clicked. You will want to pass this as a prop to your child component. Then in that component you can subscribe to it and do whatever you want when there is a click in the parent.
interface Props {
parentClick?: Observable;
}
interface State {
onClick$?: Subscription;
numClicks: number;
}
class Child extends React.Component<Props, State> {
public readonly state: State = { numClicks: 0 };
componentDidMount() {
if (this.props.parentclick) {
this.handle();
}
}
componentDidUpdate(prevProps: Props) {
if (
this.props.parentClick !== undefined &&
this.state.onClick$ === undefined
) {
this.handleSubscribe();
}
}
componentWillUnmount() {
if (this.state.onClick$) {
this.state.onClick$.unsubscribe();
}
}
handleSubscribe() {
this.setState({
onClick$: this.props.parentClick.subscribe(this.onParentClick)
});
}
#Bind()
onParentClick() {
this.setState((prevState: State) => ({
numClicks: prevState.numClicks + 1
}));
}
render() {
return (
<div style={childStyles}>
Parent clicked {this.state.numClicks} time(s)
</div>
);
}
}
So in this instance, when the parent is clicked the subscription invokes the onParentClick method. Then in that method we implement a simple counter and display it in the HTML.
One thing important thing is to ALWAYS make sure you unsubscribe from subscriptions. If you don't this will create a memory leak and will be really tricky to track down, since it is easy to overlook.

Related

Learner question: How to pass data from one class to another

I am learning spfx dev. I am creating a form with several different classes to learn how they can interact and pass data between each other.
I have two separate classes. One Parent class has a submit button which uses the Parents state to submit to a SharePoint list.
The other class component has it's own set of states and fields. I want whatever is entered by the user in the child component, to be submittable(!) by the parent class.
Here's my submit function:
private _onSubmit() {
this.setState({
FormStatus: 'Submitted',
SubmittedLblVis: true,
}, () => {
pnp.sp.web.lists.getByTitle("JobEvaluationItems").items.add({
JobTitle: this.state.JobTitle,
Faculty: this.state.Faculty,
Department: this.state.SelectedDept,
SubDepartment: this.state.SubDepartment,
DeptContactId: this.state.DeptContact,
FormStatus: this.state.FormStatus,
EvalType: this.state.EvalType,
JobTitReportTo: this.state.JobTitReportTo
}).then((iar: ItemAddResult) => {
let list = pnp.sp.web.lists.getByTitle("JobEvaluationItems");
list.items.getById(iar.data.Id).update({
JobRef: 'JE'+iar.data.Id
});
this.setState({
JobRef: iar.data.Id
});
});
});
}
Here is a function from the child component which handles whatever is typed into a field:
private _onJobTitReportToChange = (ev: React.FormEvent<HTMLInputElement>, newValue?: string) => {
this.setState({
JobTitReportTo: newValue
});
}
How would I pass the state function above (which is held within the child component) to the Parent component?
class Child extends React.Component {
state = {
childValue: 1
}
onChange = e => {
this.setState({childValue: e.target.value}, () => {
this.props.onChange(this.state);
})
}
render () {
return <input value={this.state.childValue} onChange={this.onChange} />
}
}
class Parent extends React.Component {
state = {
parentValue: 123,
dataFromChild: null
}
handleChildChange = childData => {
this.setState({dataFromChild: childData});
}
render () {
return (
<div>
<Child onChange={this.handleChildChange} />
<pre>{JSON.stringify(this.state, null, 2)}</pre>
</div>
)
}
}
ReactDOM.render(<Parent />, document.querySelector("#root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
In React world are two common used ways to transfer data:
If you want to pass it down to the child component - use props;
If you want to pass it up to the parent component - use callback;
There is another way - Context, but it's a whole different story.
if you want to pass data from one component to other.Follow the below steps.
1.PARENT --> CHILD
In parent component's render
render(){
return (
<ChildComponent data1={} data2={}/>
)
}
2.CHILD-->PARENT
make a handler in your submit function which is received to this child component from props
//CHILD COMPONENT
onSubmit=()=>{
...
//some data
...
this.props.onSubmit(data)
}
//Parent component
render(){
return(
....
<ChildComponent onSubmit={this.onSubmit}/>
....
)
}
How would I pass the state function above (which is held within the child component) to the Parent component?
It's one of React's concepts called lifting state up.
class Parent extends React.Component {
const someFunction = () => {} // move the function to the parent
render() {
return (
<>
<ChildComponent someFunction={someFunction} /> // pass function down to child
</>
)
}
}
const ChildComponent = (props) => {
return <Button onClick={props.someFunction} /> // use parent function
}

ReactJS render element by ref

I am trying to render an parent-component which has two children. The rendering of the children will switch, so one time there will be only the first child rendered, another time it will be the last and finally it will switch back to the first child (which then should contain all the values shown before).
I thought this would be simple but it turned out that it is not.
Now to the problem: Whenever the method switchContainer is called, it will switch the container and render the other. However all member-variables, props and states are getting lost and it basically reinstanciated the child-component from scratch.
Is there a way to save the child-components "as-is" and once it is getting re-rendered, it will hold all the member-variables, props and states again?
I know that you can send props and states to the element like this:
<Child props={<data>} states={<data>}>
but this doesn't solve the issue with the missing membervariables and in my opinion it isn't a smooth solution.
My attempt so far is (this is just a mockup):
class Parent extends React.Component<any,any> {
private firstContainer:any;
private secondContainer:any;
private currentContainer:any;
constructor(props:any) {
super(props);
this.firstContainer = <Child>;
this.secondContainer = <Child>;
}
public render() {
return (
<div>
{this.currentContainer}
</div>
);
}
public switchContainer() {
if(this.currentContainer === this.firstContainer) {
this.currentContainer = this.secondContainer;
}
else {
this.currentContainer = this.firstContainer;
}
this.forceUpdate();
}
}
class Child extends React.Component<any,any> {
private anyValue:string;
constructor(props) {
this.change = this.change.bind(this);
}
public render() {
return (
<input onChange={this.change} value={this.anyValue}/>
);
}
private change(e:any) {
this.anyValue = e.target.value;
}
}
You can try maintaining a state and update children in render instead of saving child as firstContainer and secondContainer
class Parent extends React.Component<any, any> {
constructor(props) {
super(props);
this.state = {
firstChild: true
};
}
public render() {
const { firstChild } = this.state;
<div>
<Child1 show={firstChild}/>
<Child2 show={!firstChild} />
</div>
}
public switchContainer() {
this.setState(({ firstChild }) => ({ firstChild: !firstChild }));
};
}
And in child component, handle show to showContent otherwise render null. If you want to retain state, you should not unmount the component.

How to setState for all instances of the same component type in that component

How to setState for all instances of the same component type in that component.
In ParentComponent
render() {
return(
<ChildComponent ... />
<ChildComponent ... />
<ChildComponent ... />
);
}
In ChildComponent
//onClick Handler should set state of all instances
onClick() {
this.setState({value: ''})
}
If you have some value which is used by multiple child components, then the correct way is to take that value one level up (i.e. in parent) and pass that value to those child as prop so that all children share the same value. So maintain a state in parent and pass them as prop to children like this
onClick() {
this.setState({value: ''})
}
render() {
return(
<ChildComponent value={this.state.value} onClick={this.onClick}... />
<ChildComponent value={this.state.value} onClick={this.onClick}... />
);
}
Ok, so...
I'm working on some kind of picker.
There are 3 components of the same type. Each component stores different state.
States depends on what user typed in input field (combined with react-autosuggest).
User fill up 3 inputs, and choose 1 image that is rendered depends on state.
After user click image, all inputs should be cleared (value is in state).
I made that working but not rly satisfied
and this is combined with redux
Parent
I made a ref to each component and save a instance to his state and pass callback to trigger methods in all child instances.
class Parent extends Component {
constructor(props) {
super(props);
this.state = {};
this.clearAllInputs = this.clearAllInputs.bind(this) // coz callback returns child own props
}
componentDidMount() {
this.setState({
firstChild: this.firstChild.getWrappedInstance(),
secondChild: this.secondChild.getWrappedInstance(),
thirdChild: this.thirdChild.getWrappedInstance(),
})
}
clearAllInputs() {
//call methods from all child instances
this.state.firstChild.clearInput();
this.state.secondChild.clearInput();
this.state.thirdChild.clearInput();
}
...
render() {
return(
<Child ref={ context => this.firstChild = context } clearAllInputs={this.clearAllInputs} ... />
<Child ref={ context => this.secondChild = context } clearAllInputs={this.clearAllInputs} ... />
<Child ref={ context => this.thirdChild = context } clearAllInputs={this.clearAllInputs} ... />
);
}
...
}
class Child extends Component {
...
clearInput() {
this.setState( { value : '' } );
}
render() {
return(
...
<img ... onClick={ this.props.clearAllInputs } />
);
}
}
export default connect(state, null, dispatchers, { withRef: true })(Child);
Since you want the same state in all of the child instances, I'd say that what you want to do is actually set the state in the parent, then pass that into all of the children as a prop. You'll need a click handler method in the parent, which you'll pass to the children as well.
Ok, I haven't tested this code, but the basic logic will be something like:
Parent
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this)
this.state = {
"value": "" // assuming 'value' is a string
}
}
handleClick(value) {
this.setState({ "value": value })
}
render() {
return(
<ChildComponent
handleClick={this.handleClick}
value={this.state.value} />
<ChildComponent
handleClick={this.handleClick}
value={this.state.value} />
<ChildComponent
handleClick={this.handleClick}
value={this.state.value} />
)
}
Child (since you talk about state of a child, setting this up as though it is a stateful component, not a presentational component)
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this)
this.state = {
"value": "" // assuming 'value' is a string
}
}
componentWillReceiveProps(nextProps) {
this.setState( {"value": nextProps.value} )
}
handleClick() {
const value = "Hey here's a value!"
props.handleClick(value) // call the parent's handleClick
}
render() {
return(
<div>
<button onClick={this.handleClick}>Set value</button>
</div>
)
}
But truth be told, I wouldn't even bother setting the state in the child - just set it in the parent and access it via props.

Dom contains or compareDocumentPosition analog in react

I have some component that contains another portaled component like
<Parent>
<Portal>
<Child>Lorem Ipsum</Child>
</Portal>
</Parent>
But on real dom it look's like:
<div class="parent"></div>
<div class="child">Lorem Ipsum</div>
I need to know, that native node of Child component is child of Parent.
Well, i had a slightly different problem. And that the Parent containes Child, we can know from event bubbling.
Portal:
class Portal extends React.Component {
el: any;
constructor(props: any) {
super(props);
this.el = document.createElement('div');
}
componentDidMount() {
document.body.appendChild(this.el);
}
componentWillUnmount() {
document.body.removeChild(this.el);
}
render() {
return ReactDOM.createPortal(
this.props.children,
this.el,
);
}
}
Child:
class Child extends React.Component {
render() {
return <div className="child">Lorem Ipsum</div>;
}
}
Parent:
class Parent extends React.Component {
target: any;
componentDidMount () {
document.addEventListener('mousedown', this.onDocMouseDown);
}
componentWillUnmount () {
document.removeEventListener('mousedown', this.onDocMouseDown);
}
onDocMouseDown = (e: any) => {
const target = e.target;
const isChild = this.target === target;
if (isChild) {
// do something
}
this.target = null;
};
onElemMouseDown = (e: any) => {
this.target = e.target;
};
render() {
return (
<div className="parent" onMouseDown={this.onElemMouseDown}>
<Portal>
<Child />
</Portal>
</div>
);
}
}
From React Portal documentation:
An event fired from inside a portal will propagate to ancestors in the
containing React tree, even if those elements are not ancestors in the
DOM tree
In Parent class we have handle for event 'mousedown' on document and on the wrapper div. When mousedown is fired, first will work wrapper handle. We save it to some variable like 'this.target'. Then event bubbling to document and in handle for document we can equal 'e.target' with 'this.target'. Accordingly we can to know is this target in Parent or not.

How to share a property with React components?

I'm new to React and I have a question about sharing properties from one component to another. For example, I want a parent component that has a "visible" function that I can pass to other child components.
Example:
CustomInput visible="true";
CustomDropDown visible="false"
I'd like to know the best way to do this, respecting good practices. Thank you for your help!
Real simple. You can pass methods as props. Suppose you have a parent, or Higher Order Component (HOC), you could do something like this:
class Parent extends React.Component {
logWord = (word) => {
console.log(word);
}
render () {
return <ChildComponent handleLogging={ this.logWord } />
}
}
Then, in the ChildComponent, you simply access the method from props. For instance:
class ChildComponent extends React.Component {
render () {
return (
<div onClick={ this.props.handleLog.bind(null, 'Logged!') }>Click me to log a word!</div>
}
}
}
So, in your example, if you wanted a method that existed on the parent that updated a visibility attribute on your state, you could write:
class Parent extends React.Component {
constructor () {
this.state = {
visible: false
}
}
setVisible = (bool) => {
this.setState({ visible: bool });
}
render () {
return <ChildComponent updateVisible={ this.setVisible } visible={ this.state.visible } />;
}
}
ChildComponent:
class ChildComponent extends React.Component {
render () {
return (
<div>
<div onClick={ this.props.updateVisible.bind(null, true) }>Set me to visible!</div>
<div onClick={ this.props.updateVisible.bind(null, false) }>Set me to invisible!</div>
{ this.props.visible && <div>I'm visible right now!</div> }
</div>
}
}
}

Resources