Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Element Properties in React Native on a Click Event

Tags:

How should I access the properties of an element without using the 'this' keyword in React Native? I have a function with which the parent class itself is bound as 'this' but I want to access the properties of the element that is being clicked. Here's the code-

import {Circle} from 'react-native-svg';
export default App extends Component {
  constructor(props) {
  super(props);
  this.state = {activeX: null}
 }

 handleTouch(event) {
   const x = event.target.cx; //How to access "cx" property here?
   this.setState({ activeX: x });
 }

 render() {
   return (
     <Circle cx='10' cy='10' r='5' onPress={this.handleTouch.bind(this)}/>
     <Circle cx='20' cy='20' r='5' onPress={this.handleTouch.bind(this)}/>
   );
 }
}
like image 944
Utkarsh Sah Avatar asked Jun 16 '17 08:06

Utkarsh Sah


People also ask

How do you get the value of clicked element in React?

To get the id of the element on click in React: Set the onClick prop on the element to a function. Access the id of the element on the currentTarget property of the event . For example, event.currentTarget.id returns the element's id .

How do you render a component on a button click?

/* Write a button component */ import React from 'react'; const Button = (props) => { return ( <button>{props. text}</button> ); } export {Button}; What is this? import React from 'react'; const ListComponent = (props) => { return ( <div> <h1>{props.

How do you show a component on button click in React?

To show or hide another component on click in React: Set the onClick prop on an element. When the element is clicked, toggle a state variable that tracks if the component is shown. Conditionally render the component based on the state variable.


2 Answers

Try this

import {Circle} from 'react-native-svg';
export default App extends Component {
  constructor(props) {
  super(props);
  this.state = {
    activeX: null,
    cx: 10
  }
 }

 handleTouch = () => {
   const x = this.state.cx
   this.setState({ activeX: x });
 }

 render() {
   return (
     <Circle cx={this.state.cx} cy='10' r='5' onPress={this.handleTouch}/>

   );
 }
}
like image 194
Kawatare267 Avatar answered Oct 11 '22 02:10

Kawatare267


import ReactNativeComponentTree from'react-native/Libraries/Renderer/src/renderers/native/ReactNativeComponentTree';

And access the properties as-

const x = ReactNativeComponentTree.getInstanceFromNode(event.currentTarget)._currentElement.props.cx;
like image 35
Utkarsh Sah Avatar answered Oct 11 '22 03:10

Utkarsh Sah