how to render component from onclick function in react? [duplicate] - javascript

I am trying to render a paragraph as soon as the you click the button.
Here is my code.
import React, { Component } from 'react';
class App extends Component {
constructor() {
super();
this.createText = this.createText.bind(this);
}
createText() {
return(
<p>hello friend</p>
)
}
render() {
return (
<div className="App">
<button onClick={this.createText}>Click</button>
</div>
);
}
}
export default App;
Here I am trying to render "hello friend" when the button is clicked. But is not working.

This is not the correct way because createText is a event handler it will not render the element, what you need is "Conditional rendering of elements".
Check Docs for more details Conditional Rendering.
Steps:
1- Use a state variable with initial value false.
2- Onclick of button update the value to true.
3- Use that state value for conditional rendering.
Working Code:
class App extends React.Component {
constructor() {
super();
this.state = {
isShow: false
}
this.createText = this.createText.bind(this);
}
createText() {
this.setState({ isShow: true })
}
render() {
return (
<div className="App">
<button onClick={this.createText}>Click</button>
{this.state.isShow && <p>Hello World!!!</p>}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'))
<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='app' />

Related

Button Content Not Updating

Style-1
Please Check both styles
import React, { Component, createRef } from 'react'
class Click extends Component {
buttonRef = createRef();
updatedValue = 0;
clickCounter = () => {
this.updatedValue = this.buttonRef.current.value++;
console.log("upDatedValue outside of render() method= "+ this.updatedValue)
}
render() {
console.log("upDatedValue inside of render() method= "+ this.updatedValue);
return (
<div>
<button ref={this.buttonRef} onClick={this.clickCounter}>
Clicked {this.updatedValue} Times</button>
</div>
)
}
}
export default Click
Style-2
import React, { Component, createRef } from 'react'
class Click extends Component {
buttonRef = createRef();
updatedValue = 0;
render() {
let clickCounter = () => {
this.updatedValue = this.buttonRef.current.value++;
console.log("upDatedValue inside of cliclCounter() method= "+ this.updatedValue);
}
console.log("upDatedValue inside of render() method= "+ this.updatedValue);
return (
<div>
<button ref={this.buttonRef} onClick={clickCounter}>
Clicked {this.updatedValue} Times</button>
</div>
)
}
}
export default Click
None of these approach is not working. It always show "Clicked 0 Times"
Can anyone please explain why this is not working and what the solution is.
Thank you.
-Samiul Fahad
You are not updating the state of your counter. Here's a solution, since you are using class based components:
class Click extends React.Component {
constructor(props) {
super(props);
this.state = {
updatedValue: 0
}
this.clickCounter = this.clickCounter.bind(this);
}
clickCounter(){
this.setState({updatedValue: this.state.updatedValue+1})
}
render() {
return (
<div>
<button onClick={this.clickCounter}>
Clicked {this.state.updatedValue} Times</button>
</div>
)
}
}
ReactDOM.render(<Click />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<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"></div>

Parent state undefined in componentDidMount event of the child component

I'm setting the state of my parent component in componentDidMount and passing its value to a child component via props, but even though the input is filled, when I run console.log(this.props.value) in the componentDidMount event of the child component, it is undefined. I need this value updated in this event.
How to get the correct prop value in this scenario?
Example code:
class Text extends React.Component {
componentDidMount(){
console.log(this.props.value);
}
render() {
return (
<div>
<input type="text" value={this.props.value} />
</div>
);
}
}
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentDidMount(){
let data = {
RequestId: "0000-000"
}
this.setState({ data });
}
render() {
return (
<Text value={this.state.data["RequestId"]} />
);
}
}
// Render it
ReactDOM.render(
<Form />,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>
What happen in your case is the child component mount before the logic change from the parent. Here a way to make it work. Also what you can do it's use the componentDidUpdate lifecycle method to trigger the change.
Remember componentDidMount get call only ONE time. So at the moment the parent get it the child is already mount. But as you can see the value of the input is filled that's because react component rerender on props change. BUT not REMOUNT.
With the if part here, the component render only when data RequestId is filled, so we can then trigger the componentDidMount with the value you want.
class Text extends React.Component {
componentDidMount(){
console.log(this.props.value);
}
render() {
return (
<div>
<input type="text" value={this.props.value} />
</div>
);
}
}
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentDidMount(){
let data = {
RequestId: "0000-000"
}
this.setState({ data });
}
render() {
if (!this.state.data["RequestId"]) { return null }
return (
<Text value={this.state.data["RequestId"]} />
);
}
}
// Render it
ReactDOM.render(
<Form />,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>

React component self close on button click

I have a react component which I want to self close when I click a button that's on the component itself.
Here's the code:
import React from 'react';
import PropTypes from 'prop-types';
const MyReactComponent = (props) => <div>
<h1>TEST</h1>
<button onClick={self close here?}>Self Close</button>
</div>
export default MyReactComponent
How can I get the button click to close the component when I click it?
That's not how React works. :-) Instead, the parent of the component should pass it a property that it uses as the onClick. In response to the click, the parent component changes its state so that the child is no longer rendered:
const MyReactComponent = (props) => <div>
<h1>TEST</h1>
<button onClick={props.onClose}>Self Close</button>
</div>;
class ParentComponent extends React.Component {
// Note: This uses the class fields proposal, currently at Stage 3 and
// commonly transpiled in React projects
closeChild = () => {
this.setState({
showChild: false
});
};
constructor(...args) {
super(...args);
this.state = {
showChild: true
};
}
render() {
return (
<div>
{this.state.showChild && <MyReactComponent onClose={this.closeChild} />}
</div>
);
}
}
ReactDOM.render(
<ParentComponent />,
document.getElementById("root")
);
<div id="root"></div>
<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>
More in the "Lifting State Up" part of the documentation.

How to render element on click of button: ReactJS

I am trying to render a paragraph as soon as the you click the button.
Here is my code.
import React, { Component } from 'react';
class App extends Component {
constructor() {
super();
this.createText = this.createText.bind(this);
}
createText() {
return(
<p>hello friend</p>
)
}
render() {
return (
<div className="App">
<button onClick={this.createText}>Click</button>
</div>
);
}
}
export default App;
Here I am trying to render "hello friend" when the button is clicked. But is not working.
This is not the correct way because createText is a event handler it will not render the element, what you need is "Conditional rendering of elements".
Check Docs for more details Conditional Rendering.
Steps:
1- Use a state variable with initial value false.
2- Onclick of button update the value to true.
3- Use that state value for conditional rendering.
Working Code:
class App extends React.Component {
constructor() {
super();
this.state = {
isShow: false
}
this.createText = this.createText.bind(this);
}
createText() {
this.setState({ isShow: true })
}
render() {
return (
<div className="App">
<button onClick={this.createText}>Click</button>
{this.state.isShow && <p>Hello World!!!</p>}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'))
<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='app' />

How to make/access state using props in react?

I made an app with multiple components and want their state to be accessed using parent/main app, I'm not sure how to get it. what i'm trying to do is when i change state in main "App" the component state should change. One of the component is 'checkbox' and now i want to access its state using parent app, I made multiple attempts but not getting it done. my code goes like this..
This is Main 'App' code:
import React, { Component } from 'react';
import Checkbox from './checkbox';
import Radio from './Radio';
import ToggleSwitch from './ToggleSwitch';
import PrimaryButton from './PrimaryButton';
class App extends Component {
onClick(isClicked){
isChecked:true
};
render() {
return (
<div id="form">
<Checkbox
onClick={this.onClick}
/>
<RadioButton
onClick={this.onClick}
/>
</div>
);
}
}
export default App;
The component i want to access goes like this:
import React, { Component } from 'react';
class Checkbox extends Component {
constructor(props){
super(props);
this.state={
isChecked:true
};
};
onCheck(){
this.setState({
isChecked: !this.state.isChecked
});
this.props.isClicked()
};
render() {
return (
<div>
<div
className={this.state.isChecked ? 'checked': 'unchecked'}
onClick={this.onCheck.bind(this)}
>
</div>
</div>
);
}
}
export default Checkbox;
You forgot to bind the onClick event in the app component, try this it will work :
class App extends Component {
onClick(isClicked){
console.log('isClicked', isClicked);
};
render() {
return (
<div id="form">
<Checkbox onClick={this.onClick.bind(this)}/>
</div>
);
}
}
If you already have onClick handler for the Checkbox I don't see why you couldn't just move the state up to the App component and just pass down a callback from there to the Checkbox that will update the parent state. That seems like a more React way to do it, to me.
class App extends Component {
constructor(props){
super(props);
this.state={
isChecked:true
}
}
onClick = (isClicked) => {
this.setState({isChecked: !this.state.isChecked})
}
render() {
return (
<div id="form">
<Checkbox
onClick={this.onClick}
ischecked={this.state.isChecked}
/>
</div>
);
}
}
Component
class Checkbox extends Component {
onCheck(){
this.props.onClick()
}
render() {
return (
<div>
<div
className={this.props.isChecked ? 'checked': 'unchecked'}
onClick={this.onCheck.bind(this)}
>
</div>
</div>
)
}
}

Categories

Resources