Reputation: 637
I'm building an application with ReactJS and would like to also use regular JavaScript for a few things, however, I'm having trouble figuring out how I would be incorporating regular JavaScript.
Let's say I have the following React-component:
class Example extends React.Component {
render() {
return (
<h1>I want to be hidden onclick</h1>
);
}
}
ReactDOM.render(<Example />, document.getElementById("whateverelement");
How would I use JavaScript in this case to hide the element onclick? Is that even possible?
I tried looking it up, however, I could only find very little results that, unfortunately, did not help very much. For example, one individual suggested defining a global function in seperate script-tags in the same file but I'm not sure if that's a good practice.
Is it common to use regular JavaScript and ReactJS in combination? How would I go about implementing it in this example?
Upvotes: 1
Views: 291
Reputation: 615
Example of how you can do this with just react is:
class Example extends React.Component {
constructor(props) {
super(props)
this.state = { visibleTitle: false }
}
onClick = () => {
this.setState({ visibleTitle: !this.state.visibleTitle })
}
render() {
const { visibleTitle } = this.state;
return (
<div>
{visibleTitle && <h1 onClick={this.onClick}>I want to be hidden onclick</h1>}
</div>
);
}
}
ReactDOM.render(<Example />, document.getElementById("whateverelement");
Ofcourse, modern state management libraries can replace the this.state
Upvotes: 1
Reputation: 27
class Example extends React.Component {
onClickFunction() {}
render() {
return (
<h1 onclick={onClickFunction}>I want to be hidden onclick</h1>
);
}
}
ReactDOM.render(<Example />, document.getElementById("whateverelement");
You can write JS in the React element by opening and closing curly brackets
Upvotes: 1