Returning a function in React

A have a box that, upon clicking on it, should have the word “Hello” displayed inside of it. I realize there’s something I’m missing with the onClick event, but I can’t think of a way to insert that function in the div. I tried simply returning 'Hello' and also using e.target but it’s not working. https://codepen.io/Montinyek/pen/abGWyZN?editors=1111

you have to first check the condition where click event is happened on the div
by something like if i give className=container

‘’’

"e.target.className==="container "
‘’’
please check by console. log(e.target) on click event then you will have better idea.

Sorry i’m not sure what you mean

If you want to change the text on a click, your onClick should call setState to change the state. And you display that state on the screen.

There’s no way of doing that without using state?

That is pretty much the point of React.

No, you do not have to use state, but not using state completely defeaters the purpose of using React and then you might as well code it in plain JS.

Okay, I’m just trying to understand the mechanics of React. So how would I do this without using state?

You wouldn’t that is the point. You need to use state otherwise you are breaking the reactiveness of the app.

The point is you have a variable, it is tracked and when it changes any reference to it in the JSX is automatically updated to reflect that change. You do not manually update the DOM, you just change the tracked variables.

You can do plain JS DOM manipulation, React doesn’t stop you, but that is absolutely not something you should do with React. But you would do it the same way as in a plain JS app, grab the element and change its content. Again, do not do this in React.


Example
class Show extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: "Initial text"
    };
    this.text = this.text.bind(this);
  }

  text() {
    this.setState({
      text: "Hello"
    });
  }

  render() {
    return <div onClick={this.text}>{this.state.text}</div>;
  }
}

const App = () => (
  <div className="box m-auto text-center">
    <Show />
  </div>
);

ReactDOM.render(<App />, document.getElementById("yo"));

That is the point of state. You want the “state” of the component to change. “state” is just memory. You can hard code that value in, but then you couldn’t change it (at least not with React, through normal means). So it has to be dynamic memory. In React, that’s state. Or you could pass it in on props, which means it would be state somewhere else.

Why are you afraid of state?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.