1

I was trying to create a very small react app that has a button with a latex-symbol which, when clicked, displays how one can include that symbol in latex. I'm using an npm package ("react-katex") to render latex code on the browser. The button renders fine, but when I click on the button, I don't get the desired result.

I've structured my app so that I have a parent component (App) which has a child component (Latex) which has the button. I thought of using the value attribute of the button tag to pass the value to the parent on an "onClick" event. That way, in the onClick event handler, I could use the event.target.value attribute to achieve my purpose. However, event.target doesn't even refer to the button when I run the program. Here's a snipped of code:

For the App component:

constructor(){ super(); this.state = { symbolName: '' }; } onButtonClick = (event) => { console.log(event.target) } render(){ return( <div className='tc'> <Latex buttonClick={this.onButtonClick}/> <h1> {this.state.symbolName} </h1> </div> ); } 

for the Latex component:

const Latex = ({ buttonClick }) => { return ( <div className='tc'> <button onClick={buttonClick} value={latexSymbols[0]}> <InlineMath> {latexSymbols[0]} </InlineMath> </button> </div> ); } 

So, on clicking the button, instead of getting something along the lines of <button value={latexSymbols[0]}>...</button>, the output I get is <span class="mrel amsrm">...</span>. I'm assuming this is how the react-katex package renders the latex-symbol. But this is confusing me since the symbol wasn't the target of the event, the button was. Is there a work-around this problem?

3 Answers 3

1

Answer:

Instead of using event.target use event.currentTarget

onButtonClick = (event) => { console.log(event.currentTarget) } 

Why?

event.target is the thing that is clicked on. Because you have a component within your button, it's going to be that, not the button.

event.currentTarget is the thing that actually has the event listener attached to it. In this case, button.


Sign up to request clarification or add additional context in comments.

Comments

1

target not always refers to the element that has the handler attached on (it refers to element that triggered the click). You should use currentTarget which represents the element that the event listener is attached to.

onButtonClick = (event) => { console.log(event.currentTarget) } 

Comments

0

You can do it like this buttonClick is a callback function if you need a value just pass button value instead of the event in a case when you will need button value and event together
onClick={(event) => buttonClick(event, latexSymbols[0])} use something like this

const Latex = ({ buttonClick }) =*emphasized text*> { return ( <div className='tc'> <button onClick={() => buttonClick(latexSymbols[0])} value={latexSymbols[0]}> <InlineMath> {latexSymbols[0]} </InlineMath> </button> </div> ); }

Comments