I have a component in which there is a checkbox and on on Changed event of checkbox ,i want to display a message saying it is checked or not .
There is no error in VS Code ,and when i tried debugging the code did fire on Changed event and called the tick function and call the setstate,but then when i step into next line ,it goes into some internal React javascript files which i find hard to understand ,to figure out the problem . Presently i get a checkbox ,but on checking or unchecking the message does not change
import React,{ Component } from 'react';
class Checked extends Component{
constructor(props)
{
super(props);
this.state= {check: true};
}
tick()
{
this.setState({check:!this.state.check});
}
render(){
var msg="";
if ( this.state.check=true)
{
msg="checked";
}
else
{
msg="unchecked";
}
return(<div><input type="checkbox" onChange={this.tick.bind(this)} defaultChecked={this.state.check} ></input>
<h1>checkbox is {msg}</h1>
</div> );
}
}
export default Checked;
You can also add the logic in the function, this implementation works for me
import React from 'react';
import { render } from 'react-dom';
class Checked extends React.Component {
constructor(props) {
super(props);
this.tick = this.tick.bind(this);
this.state = {
checkBox: true,
checkedMsg: ''
}
}
tick() {
this.setState({
checkBox: !this.state.checkBox
})
this.state.checkBox ? this.setState({ checkedMsg: 'checked' }) : this.setState({ checkedMsg: 'unchecked' })
}
render() {
return (
<div>
<input
type="checkbox"
onClick={this.tick}
defaultChecked={this.state.check}
/>
<h1>checkbox is {this.state.checkedMsg}</h1>
</div>
);
}
}
export default Checked;
render(<Checked />, document.getElementById('root'));
Related
I want to change defaultInputValue of Typehead component if the state gets updated.
I am using react.
import React, { Component } from 'react';
import { Typeahead } from "react-bootstrap-typeahead";
export default class TypeHead extends Component{
constructor(props) {
super(props);
this.state = {
text : ""
};
render(){
<Typeahead
id="basic-typeahead-single"
labelKey="selectedVariableInField"
onChange={(selected)=>{
const selectedVariable = (selected.length > 0) ? selected[0] : "";
this.setState({text: selectedVariable })
}}
options={this.state.variables}
onInputChange={(text, event) => {
this.setState({text: text})}
placeholder="Enter Variable"
defaultInputValue= {this.state.text}
/>
}
}
the above code is not updating the defaultInputValue value even if the state gets updated
Once I click the text box some of my div will show a "typing." Before clicking, it should show "this is just a sample."
<input type="text" onClick={this.state}>
Although your question is really messy, here's the sample code for you. Maybe it'll point you the right direction.
import React from "react";
export default class Test extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
someState: ""
}
this.onChangeState = this.onChangeState.bind(this);
}
onChangeState(e) {
this.setState({
someState: //logic here
})
}
render() {
const {someState} = this.state;
return (
<>
<input type="text" onClick={e => this.onChangeState(e)}>
State value: {someState}
</>
)
}
}
Whenever you click chosen div, you'll call onChangeState method where you can manipulate your state. Don't forget that every state update causes rerender.
For more info visit official React docs.
if I understood correctly you want to display the word 'Typing' once you click on the div.
I think this will help you
import React from "react";
export default class Typing extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
yourStateName: ""
}
this.onChangeState = this.onChangeState.bind(this);
}
onChangeState(e) {
this.setState({
yourStateName: "Typing"
})
}
render() {
const {yourStateName} = this.state;
return (
<div>
<input type="text" onClick={e => this.onChangeState(e)}>
value: {yourStateName}
<div/>
)
}
}
I made a text input box which, when submitted, will update the state of the messages in the parent component. The messages in the parent component are passed down to the message display. I'd like the component responsible for displaying the messages to update and display the messages after each submission, but can't figure out how to do it. I made a code sandbox here:
https://codesandbox.io/s/unruffled-pasteur-nz32o
Here's my code:
Parent component:
import React, { Component } from "react";
import Messages from "./Messages";
import Input from "./Input";
export default class Container extends Component {
constructor(props) {
super(props);
this.state = {
messages: []
};
}
updateMessage(message) {
this.state.messages.push(message);
}
render() {
return (
<div>
<Messages messages={this.state.messages} />
<Input updateMessage={message => this.updateMessage(message)} />
</div>
);
}
}
Message input component:
import React, { Component } from "react";
export default class Input extends Component {
constructor(props) {
super(props);
this.state = {
message: ""
};
}
sendMessage() {
this.props.updateMessage(this.state.message);
this.setState({ message: "" });
}
render() {
return (
<div>
<input
type="text"
value={this.state.message}
onChange={({ target }) => {
this.setState({ message: target.value });
}}
/>
<button onClick={() => this.sendMessage()}>Send</button>
</div>
);
}
}
Message display component:
import React, { Component } from "react";
export default class Messages extends Component {
render() {
return this.props.messages.map(message => {
return <div>{message}</div>;
});
}
}
Thanks!
From your code:
updateMessage(message) {
this.state.messages.push(message);
}
You're modifying the state directly and you're not supposed to do that (except for in the constructor). It won't cause a re-render in this way. Instead, clone the state, modify it, then update the state via setState. Calling setState will invoke a re-render.
updateMessage(message) {
this.setState({
messages: [...this.state.messages, message],
});
}
In your updateMessage(message) method, can you try:
updateMessage(message) {
let { messages } = this.state;
messages.push(message)
this.setState({ messages })
}
Your error is in this part
updateMessage(message) {
this.state.messages.push(message);
}
You can not change state directly. You must use setState() method to change state
updateMessage(message) {
this.setState({
messages : [...this.state.messages, message]
});
}
I'm importing a class from another script in my main React App, and would like to access a variable within that class from the main App. Basically the user types something into a textbox, then clicks a button to add that value to a variable. In the main App I import that class, then have another button to print those values (selectedvalues). I'm not entirely sure how to do it, but this is my code so far:
Class I am importing:
import React, { Component } from 'react';
class MyModule extends Component {
constructor() {
super();
this.state = {
selectedValues: '',
}
}
addValue() {
this.selectedValues += document.getElementById('textBox1').value + ', '
return this.selectedValues
}
render() {
return(
<div>
<input type='text' id='textBox1' />
<button onClick={() => this.addValue()}>Add Value</button>
</div>
)
}
}
export default MyModule
And where I would like to actually access that value
import React, { Component } from 'react';
import MyModule from './myModule.js'
class App extends Component {
constructor() {
super();
this.state = {
}
}
printValues() {
console.log(document.getElementById('themodule').selectedvalues)
}
render() {
return(
<MyModule id='themodule' />
<button onClick={() => printValues()}>Print values</button>
)
}
}
export default App
Is there a way I can do this?
Thanks!
Edit JS-fiddle here https://jsfiddle.net/xzehg1by/9/
You can create Refs and access state and methods from it. Something like this.
constructor() {
this.myRef = React.createRef();
}
render() { ... <MyModule id='themodule' ref={this.myRef} /> }
printValues() {
console.log(this.myRef)
}
more info here https://reactjs.org/docs/refs-and-the-dom.html
Basically, your state (selectedValues) has to go one level up in the React tree. You have to declare it as App's state, and then pass it down to MyModule via props.
Btw in addValue(), you're not changing any state. And this.selectedValues will be undefined. It's this.state.selectedValues, and this.props.selectedValues once you correct your code.
I think you should first read all react concepts and then start working on it. Anyhow i am modifying your code in one way to get your desired functionality but remember this is not best practice you have to use Redux for this kind of features
import React, { Component } from 'react';
class MyModule extends Component {
constructor() {
super(props);
this.state = {
inputValue : ''
};
this.handleInput = this.handleInput.bind(this);
this.addValue = this.addValue.bind(this)
}
handleInput(e){
this.setState({
inputValue : e.target.value
})
}
addValue() {
this.props.addValue(this.state.inputValue);
}
render() {
return(
<div>
<input type='text' id='textBox1' onChange={handleInput} />
<button onClick={this.addValue}>Add Value</button>
</div>
)
}
}
export default MyModule
and your main component should be
import React, { Component } from 'react';
import MyModule from './myModule.js'
class App extends Component {
constructor() {
super(props);
this.state = {
selectedValues : ''
};
this.printValues = this.printValues.bind(this);
this.addValues = this.addValues.bind(this);
}
printValues() {
console.log(this.state.selectedValues);
}
addValues(val){
this.setState({
selectedValues : this.state.selectedValues + " , "+val
})
}
render() {
return(
<React.Fragment>
<MyModule addValue={this.addValues}/>
<button onClick={this.printValues} >Print values</button>
</React.Fragment>
)
}
}
export default App
This should do your work
I want to create a button so that when i click on it, it makes a text appear, and on second click, disappears, on third, appears again... and so on.
class App extends Component {
constructor() {
super();
this.state = {
isShow: false,
}
this.createText = this.createText.bind(this);
this.condrender = this.condrender.bind(this);
}
createText() {
this.setState({ isShow: true });
}
condrender() {
if (this.state.isShow===true) {
return (
<p>THIS TEXT</p>
);
}
}
render() {
return (
<div className="App">
<button onClick={this.createText}>Click</button>
{this.condrender()}
</div>
);
}
}
}
With this code, the text appears when i click on the button. So I added this line this.setState({isShow: false}), and I get an error.
condrender() {
if (this.state.isShow===true) {
this.setState({isShow: false})
return (
<p>THIS TEXT</p>
);
}
}
Warning: Cannot update during an existing state transition (such as
within render or another component's constructor). Render methods
should be a pure function of props and state; constructor side-effects
are an anti-pattern, but can be moved to componentWillMount
My thinking is that after I set it to false, the text will disappear since isShow's state will be false. Please help me understand the error and how to go around this?
This warning is shown, as you are calling a method in render method and then trying to set state in that method.
Instead, what you can do is :
class App extends Component {
constructor() {
super();
this.state = {
isShow: false,
}
this.createText = this.createText.bind(this);
this.condrender = this.condrender.bind(this);
}
createText() {
this.setState({ isShow: !this.state.isShow});
}
condrender() {
return (
<p>THIS TEXT</p>
);
}
}
render() {
return (
<div className="App">
<button onClick={this.createText}>Click</button>
{this.state.isShow ? this.condrender() : null}
</div>
);
}
}
}
Hope it helps.
It's pretty straight foward. On every click you just set the state to the opposite of itself. You can use a ternary to render.
import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
class App extends React.Component
{
constructor()
{
super();
this.state =
{
isShow: false,
}
this.ToggleText = this.ToggleText.bind(this);
}
ToggleText()
{
let state = { ...this.state };
state.isShow = !state.isShow;
this.setState(state);
}
render()
{
let element = <p>THIS TEXT</p>
return (
<div className="App">
<button onClick={this.ToggleText}>Click</button>
{
this.state.isShow ? element : null
}
</div>
);
}
}
render(<App />, document.getElementById('root'));
Set state to the nagative of the previous state and all will be done !
createText() {
this.setState({ isShow: !this.state.isShow });
}