How do I display text on button click in React.js - html

Have this code (below) and am trying to display the text at the click of a button in React.js.
Heres the code:
class App extends Component{
render(){
alert=()=>{return(<h1>Hi</h1>)}
return(<div className="App">
<button onClick={this.alert}>Enter</button>
</div>);
}}
export default App;
Any ideas why it's not working...?

If you want to display it in an alert window, you need to call a function to trigger the window.
class App extends Component{
onButtonClickHandler = () => {
window.alert('Hi')
};
render(){
return(<div className="App">
<button onClick={this.onButtonClickHandler}>Enter</button>
</div>);
}
}
However, if you need to show the message in your render, you can use a state to manage that.
class App extends Component{
state = {
showMessage: false
}
onButtonClickHandler = () => {
this.setState({showMessage: true});
};
render(){
return(<div className="App">
{this.state.showMessage && <p>Hi</p>}
<button onClick={this.onButtonClickHandler}>Enter</button>
</div>);
}
}
Source code:
If you need to toggle the text on button click, you just need to update the onButtonClickHandler function to this.setState({ showMessage: !this.state.showMessage });.

It won't display as like that. Here you are calling alert function and returning some JSX. How react will know where to render?. Do it like below.
class TodoApp extends React.Component {
constructor(props) {
super(props)
this.state = {
render: false
}
this.alertHi = this.alertHi.bind(this);
}
alertHi() {
this.setState({render: !this.state.render});
}
render() {
return(
<div className="App">
<button onClick={this.alertHi}>Enter</button>
{this.state.render && <h1>Hi</h1>}
</div>
);
}
}
Demo

Related

Pass image link as props

I wanted to pass image link through 2 child components. I put my link inside state and passed it but it's not working. When I manually put link in child component it's working the way it should. What is the matter, can't figure it out.
class App extends React.Component{
state = {
currentImage: 'http://steemitimages.com/640x0/https://steemitimages.com/DQmZ5ZTZGH7odGrk3N7m6xvn2tS4Uz5G2RtkN5A2mM1GZnk/Lucius-Seneca-451x500.png',
}
render(){
return (
<>
<Window
image={this.state.currentImage}
/>
<Form/>
</>
);
}
}
//First Child
class Window extends React.Component {
render() {
return (
<div className={styles.wrapper}>
<div className={styles.content}>
<Quote image={this.props.image}/>
</div>
</div>
)
}
}
//Target child that should display pic
class Quote extends React.Component {
render() {
return(
<div className={styles.wrapper}>
<img
src={this.props.image}
className={styles.image}
/>
</div>
)
}
}
I think you should make a constructor.
class App extends React.Component{
constructor(props) {
super(props);
this.state = {
currentImage: 'https://steemitimages.com/DQmZ5ZTZGH7odGrk3N7m6xvn2tS4Uz5G2RtkN5A2mM1GZnk/Lucius-Seneca-451x500.png'
};
}
render(){
return (
<>
<Window
image={this.state.currentImage}
/>
<Form/>
</>
);
}
}
There is no problem with props.. Just you misused state in App component.

React JSX on html

I try to insert react on simple HTML file. There is an official example on https://reactjs.org/docs/add-react-to-a-website.html#add-jsx-to-a-project but I don't understand how to render a JSX-encoded component and how to insert a component into another component :
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return "You liked this.";
}
// Display a "Like" <button>
return <button onClick={() => this.setState({ liked: true })}>Like</button>;
}
}
const domContainer = document.querySelector("#like_button_container");
ReactDOM.render(LikeButton, domContainer);
So you've likely already followed the directions to import React and ReactDOM into your HTML:
<!-- depends where it's hosted -->
<script src="react.min.js"></script>
<script src="reactdom.min.js"></script>
Then you add your custom JS to the HTML as well:
<!-- this goes right before the closing body tag -->
<script src="custom-like-button.js"></script>
And lastly you put an HTML element where you want the component to render and make sure it has an id that matches the querySelector at the end of the React example:
<div id="custom-like-button"></div>
As for nested components, you can nest them inside the return of the top-level component (the one that's being injected into the DOM)
class MyComponent extends React.Component {
render() {
return <LikeButton />
}
}
class LikeButton extends React.Component {
render () {
return <button onClick={() => this.setState({ liked: true })}>Like</button>;
}
}
// goes inside <div id="my-component"></div> in html
const domContainer = document.querySelector("#my-component");
ReactDOM.render(MyComponent, domContainer);

How can a function value is displayed in a HTML tag with a return value from addEventListerner click?

I am trying to build a calculator and want to print digits on the screen. I have not yet put the calculator algorithm, just only to print the digits on the screen.
const Keys = ({calcKeys})=>(<div className="display-keys">
<div className="screen"><handleClick></div>
{calcKeys.map((item)=>{
return <button className="display-keys">{item.key}</button>
})
}
class App extends React.Component { constructor(props) { super(props);
this.state={calcKeys:[{"key": "AC"},{"key": "CE"},{"key": "±"},{"key": "/"},{"key": "7"},{"key": "8"},{"key": "9"},{"key": "x"},{"key": "4"},{"key": "5"},{"key": "6"},{"key": "-"},{"key": "1"},{"key": "2"},{"key": "3"},{"key": "+"},{"key": "."},{"key": "0"}]};}
this.displayKeys = this.displayKeys.bind(this)];
const keyButton = document.querySelector('.display-keys');
handleClick() {
keyButton.addEventListener('click', (e) => {
return const keyPad = e.key;
});
}
render(){
return(
<div className="display-container">
<Keys calcKeys={this.state.calcKeys}/>
</div>
);
}
}
ReactDOM.render( <App />, document.getElementById("root"));
For this case, if you want to click on the button you don't need to add an addEventListener.
As you are using React, you can create a function to handle click.
If you want to handle a keypress on the keyboard, that's the case to use addEventListener.
I changed your code a bit in order to make it work as expected. I didn't add any logic to make the calculator work but clicking on any button will add it to state and display on "screen".
This is what I did:
// "Keys" Component receives the calcKeys and the handleClick function.
// It uses the handleClick function on the button onClick passing the current item key
const Keys = ({ calcKeys, handleClick }) => (
<div className="display-keys">
{calcKeys.map(item => (
<button onClick={() => handleClick(item.key)}>{item.key}</button>
))}
</div>
)
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
calcKeys: [{"key": "AC"},{"key": "CE"},{"key": "±"},{"key": "/"},{"key": "7"},{"key": "8"},{"key": "9"},{"key": "x"},{"key": "4"},{"key": "5"},{"key": "6"},{"key": "-"},{"key": "1"},{"key": "2"},{"key": "3"},{"key": "+"},{"key": "."},{"key": "0"}],
value: '',
};
this.handleClick = this.handleClick.bind(this)
}
// Here I just receive the key and add it to state.
// This is the place to add logic, check if the key is "AC" for example and clean the state, etc.
handleClick(key) {
const { value } = this.state
this.setState({ value: `${value}${key}` })
}
render() {
const { value } = this.state
return (
<div className="display-container">
<div className="screen">{value}</div>
<Keys calcKeys={this.state.calcKeys} handleClick={this.handleClick} />
</div>
);
}
}
You can test it in a working JSFiddle here

React: Render JSX repeatedly with multiple onClicks

I followed this stackoverflow answer however i want to know how i can modify this to have it render jsx again & again with multiple clicks
here's a CodePen to show it in action
class NewComponent extends React.Component {
render() {
return (
<div {...this.props}>
new component
</div>
);
}
}
class Button extends React.Component {
render() {
return (
<button {...this.props}>
click
</button>
);
}
}
class App extends React.Component {
constructor() {
super();
this.state = {
clicked: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
clicked: true
});
}
render() {
return (
<div>
<Button onClick={this.handleClick} />
{this.state.clicked ? <NewComponent /> : null}
</div>
);
}
};
ReactDOM.render(
<App />,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root">loading...</div>

Render view on click Reactjs

I have created a overlay element and I want it to appear when a certain input field is clicked. I'm new to react so it's not clear to me how I should do it.
This is the view that should appear
import React, { Component } from 'react';
import pro_pic from '../../Resources/img/Anon.jpg';
import menu_drop from '../../Resources/img/drop.png';
class QuestionOverlay extends Component {
render() {
return (
<div id="overlay">
</div>
)
}
}
export default QuestionOverlay;
The click event is here
render() {
function popup_ques(e) {
e.preventDefault();
alert("render overlay view");
}
return (
<div className="middle_div">
<input className='post_data_input' placeholder="Ask your question here" ref="postTxt"
onClick={popup_ques}/>
</div>
);
}
So when I click the input field, the overlay I have created should appear instead of the alert I have given.
This is what I would do:
constructor(props) {
super(props);
this.state = {
overlayVisible: false
}
}
render() {
function popup_ques(e) {
e.preventDefault();
this.setState({
overlayVisible: true
});
}
return (
<div className="middle_div">
<input
className='post_data_input'
placeholder="Ask your question here"
ref="postTxt"
onClick={popup_ques}/>
{this.state.overlayVisible && <QuestionOverlay />}
</div>
);
}
Your function has to be pure, so, based on a state you get an UI render, if you want to insert something, you change your state, but your render function remains the same.
However that approach effectively constructs a new overlay every time you show it, if you want to keep the state perhaps it is better to keep the component but change it's rendering:
import React, { Component } from 'react';
class QuestionOverlay extends Component {
render() {
if(!this.props.visible) {
return null
}
return (<div id="overlay"/>)
}
}
export default QuestionOverlay;
And the container:
constructor(props) {
super(props);
this.state = {
overlayVisible: false
}
}
render() {
function popup_ques(e) {
e.preventDefault();
this.setState({
overlayVisible: true
});
}
return (
<div className="middle_div">
<input
className='post_data_input'
placeholder="Ask your question here"
ref="postTxt"
onClick={popup_ques}/>
<QuestionOverlay visible={this.state.overlayVisible}/>
</div>
);
}