React changing input type via event - javascript

I'm trying to extend a React input component, which needs to be type password and after certain event on the element or element next to it - it needs to toggle the type of the input (type="text/password").
How this can be handled by React?
I have this as class for my component:
import { React, Component } from 'lib'
export class PasswordInput extends Component {
constructor(props, context){
super(props, context)
const { type, validate, password } = this.props
if(context.onValidate && password) {
context.onValidate(password, validate)
}
if(context.showHide && password) {
context.onValidate(password, validate)
}
}
render() {
let inputType = 'password'
return (
<div className="form">
<label htmlFor="password">{ this.props.label }</label>
<input {...this.constructor.filterProps(this.props)} type={ inputType } />
{ this.props.touched && this.props.error && <div className="error">{ this.props.error }</div> }
<button onClick={ showHide() }>{ this.props.btnLabel }</button>
</div>
)
}
showHide(field) {
return function(event){
console.log(`state before is ${this.state}`)
}
}
// the meld is
// export function meld(...objects) {
// return Object.assign({}, ...objects)
// }
static filterProps(props) {
const result = meld(props)
delete(result.validate)
return result
}
}
PasswordInput.contextTypes = {
onValidate: React.PropTypes.func
}
EDIT
I've edited the render method and added a function that handles the event, but I'm now getting:
Warning: setState(...): Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state.
And my browser crashes.
.....
render() {
return (
<div className="form__group">
<label htmlFor="password">{ this.props.label }</label>
<input {...this.constructor.filterProps(this.props)} type={ this.state.inputType } />
{ this.props.touched && this.props.error && <div className="form__message form__message_error">{ this.props.error }</div> }
<button onClick={ this.handleClick() }>{ this.props.btnLabel }</button>
</div>
)
}
handleClick(){
this.setState({ inputType: this.state.inputType === 'password' ? 'text' : 'password' })
}
.....

You can configure the type of the input according to component's state, and set it on some event, for example:
<input {...this.constructor.filterProps(this.props)} type={ this.state.inputType } onChange={ event => this.onChange(event) } />
And implement the onChange method:
onChange(event) {
var length = event.currentTarget.value.length;
this.setState({ inputType: length < 5 ? 'text' : 'password' });
}
You might have to bind the onChange function.

Related

How to update state of one component in another in react class component. Save Functionality

How to update state of one component in another in react class component.
I have two class in reacts.
MyComponent and MyContainer.
export default class MyContainer extends BaseComponent{
constructor(props: any) {
super(props, {
status : false,
nameValue :"",
contentValue : ""
});
}
componentDidMount = () => {
console.log(this.state.status);
};
save = () => {
console.log("Hello I am Save");
let obj: object = {
nameValue: this.state.nameValue, // here I am getting empty string
templateValue: this.state.contentValue
};
// API Call
};
render() {
return (
<div>
<MyComponent
nameValue = {this.state.nameValue}
contentValue = {this.state.contentValue}
></MyComponent>
<div >
<button type="button" onClick={this.save} >Save</button>
</div>
</div>
);
}
}
MyComponent
export default class MyComponent extends BaseComponent{
constructor(props: any) {
super(props, {});
this.state = {
nameValue : props.nameValue ? props.nameValue : "",
contentValue : props.contentValue ? props.contentValue : "",
status : false
}
}
componentDidMount = () => {
console.log("MOUNTING");
};
fieldChange = (id:String, value : String) =>{
if(id === "content"){
this.setState({nameValue:value});
}else{
this.setState({contentValue:value});
}
}
render() {
return (
<div>
<div className="form-group">
<input id="name" onChange={(e) => {this.fieldChange(e)}}></input>
<input id = "content" onChange={(e) => {this.fieldChange(e)}} ></input>
</div>
</div>
);
}
}
In MyComponent I have placed two input field where on change I am changing the state.
Save button I have in MyContainer. In save button I am not able to read the value of MyComponent. What is the best way to achieve that.
You should be updating your state in MyContainer for save to have visibility of the state changes. Each component gets its own state, which makes MyComponent's state unique to that of MyContainer. What you should be doing is keeping the state in your parent/container component, and then passing it down as props (rather than duplicating it in your child). To do this, move fieldChange up to the MyContainer function, and remove the duplicate nameValue and contentValue state within MyComponent. See code commennts for further details:
export default class MyContainer extends BaseComponent{
...
fieldChange = (id:String, value : String) =>{
if(id === "content"){
this.setState({nameValue: value});
} else {
this.setState({contentValue: value});
}
}
render() {
return (
<div>
<MyComponent
nameValue={this.state.nameValue}
contentValue={this.state.contentValue}
onFieldChange={this.fieldChange} /* <---- Pass the function down to `MyComponent` */
/>
...
</div>
);
}
}
Then in MyComponent, call this.props.onFieldChange:
export default class MyComponent extends BaseComponent{
// !! this constructor can be removed as no state is being initialized anymore !!
constructor(props: any) {
super(props);
// removed state as we're using the state from `MyContainer`
}
componentDidMount = () => {
console.log("MOUNTING");
};
render() {
return (
<div>
<div className="form-group">
<input id="name" onChange={(e) => {this.props.fieldChange(e)}} /> /* <--- Change to `this.props.fieldChange()`. `<input />` is a self-closing tag.
<input id = "content" onChange={(e) => {this.props.fieldChange(e)}} />
</div>
</div>
);
}
}
Some additional notes:
If your component doesn't use this.props.children, then you should call it as <MyComponent ... props ... /> not <MyComponent ... props ...></MyComponent>
Your if-statement in your fieldChange looks reversed and should be checking if(id === "name"). I'm assuming this is an error in your question.
You're only passing one argument to fieldChange in your example code. I'm again assuming this in an error in your question.

React: 2 way binding props

How can I do a 2 way binding of a variable from the parent component (Form.js), such that changes occurred in the child component (InputText.js) will be updated in the parent component?
Expected result: typing values in the input in InputText.js will update the state of Form.js
In Form.js
render() {
return (
<div>
<InputText
title="Email"
data={this.state.formInputs.email}
/>
<div>
Value: {this.state.formInputs.email} // <-- this no change
</div>
</div>
)
}
In InputText.js
export default class InputText extends React.Component {
constructor(props) {
super(props);
this.state = props;
this.handleKeyChange = this.keyUpHandler.bind(this);
}
keyUpHandler(e) {
this.setState({
data: e.target.value
});
}
render() {
return (
<div>
<label className="label">{this.state.title}</label>
<input type="text" value={this.state.data} onChange={this.handleKeyChange} /> // <-- type something here
value: ({this.state.data}) // <-- this changed
</div>
)
}
}
You can manage state in the parent component itself instead of managing that on child like this (lifting state up):
In Form.js
constructor(props) {
super(props);
this.handleKeyChange = this.keyUpHandler.bind(this);
}
keyUpHandler(e) {
const { formInputs } = this.state;
formInputs.email = e.target.value
this.setState({
formInputs: formInputs
});
}
render() {
// destructuring
const { email } = this.state.formInputs;
return (
<div>
<InputText
title="Email"
data={email}
changed={this.handleKeyChange}
/>
<div>
Value: {email}
</div>
</div>
)
}
In InputText.js
export default class InputText extends React.Component {
render() {
// destructuring
const { title, data, changed } = this.props;
return (
<div>
<label className="label">{title}</label>
<input type="text" value={data} onChange={changed} />
value: ({data})
</div>
)
}
}
You can also make your InputText.js a functional component instead of class based component as it is stateless now.
Update: (How to reuse the handler method)
You can add another argument to the function which would return the attribute name like this:
keyUpHandler(e, attribute) {
const { formInputs } = this.state;
formInputs[attribute] = e.target.value
this.setState({
formInputs: formInputs
});
}
And from your from you can send it like this:
<input type="text" value={data} onChange={ (event) => changed(event, 'email') } />
This assumes that you have different inputs for each form input or else you can pass that attribute name also from parent in props to the child and use it accordingly.
You would need to lift state up to the parent
parent class would look something like
onChangeHandler(e) {
this.setState({
inputValue: e.target.value // you receive the value from the child to the parent here
})
}
render() {
return (
<div>
<InputText
title="Email"
onChange={this.onChangeHandler}
value={this.state.inputValue}
/>
<div>
Value: {this.state.inputValue}
</div>
</div>
)
}
children class would look something like
export default class InputText extends React.Component {
constructor(props) {
super(props);
this.state = props;
}
render() {
return (
<div>
<label className="label">{this.state.title}</label>
<input type="text" value={this.state.value} onChange={this.props.onChange} />
value: ({this.state.value})
</div>
)
}
}
You can simply pass a callback from Form.js to InputText and then call that callback in InputText on handleKeyChange

Passing props from search, Won't setState

I made a search component, I am passing the results of the search back to the parent using props. The issue is it will not setState until the function is triggered so I get the error of undefined in the map loop.
I am trying to show all results until the search is triggered using onChange.
How can I accomplish this.
//Search Component
export default class Searchbar extends Component {
constructor(props){
super(props)
}
state = {
input : '',
visable:[],
}
onChange=(e)=>{
this.setState({input: e.target.value})
let clone = [...this.props.theGitUsers]
if(e.value === ''){
this.setState({visable:clone})
}else{
let filteredSearch = clone.filter((loginUsers)=>{
return loginUsers.login.toUpperCase().includes(this.state.input.toUpperCase())
})
this.setState({visable:filteredSearch})
}
//Passing the state results to App Component using this props to the App function function
this.props.searchRes(this.state.visable);
}
render() {
return (
<div>
<input type="text" onChange= {this.onChange} value={this.state.input} />
</div>
)
}
}
//App.js Parent ////////////////////////
state={
gitusers:[],
searched:[],
loading:false,
}
componentDidMount(){
this.setState({loading:true});
setTimeout(() => {
axios.get('https://api.github.com/users')
.then(res=> this.setState({gitusers:res.data , loading:false}))
}, 1000);
}
//The search results from Searchbar Component
searchRes=(visable)=>{
this.setState({searched:visable})
}
render(){
return (
<div>
<Navbar title="Github Finder" icons="fab fa-github" />
<Searchbar theGitUsers = {this.state.gitusers} searchRes = {this.searchRes} />
<div className = "container">
<TheUsers gituser = {this.state.gitusers} loading={this.state.loading} />
</div>
</div>
);
}
Always check for empty or null while running map over array.
userSearch && userSearch.map(item => {
console.log(item);
});

Stop Relay: Query Renderer in reloading data for certain setStates

I'm currently following this and I did get it to work. But I would like to know if there is a way to stop the Query Render from reloading the data when calling this.setState(). Basically what I want is when I type into the textbox, I don't want to reload the data just yet but due to rendering issues, I need to set the state. I want the data to be reloaded ONLY when a button is clicked but the data will be based on the textbox value.
What I tried is separating the textbox value state from the actual variable passed to graphql, but it seems that regardless of variable change the Query will reload.
Here is the code FYR.
const query = graphql`
query TestComponentQuery($accountId: Int) {
viewer {
userWithAccount(accountId: $accountId) {
name
}
}
}
`;
class TestComponent extends React.Component{
constructor(props){
super(props);
this.state = {
accountId:14,
textboxValue: 14
}
}
onChange (event){
this.setState({textboxValue:event.target.value})
}
render () {
return (
<div>
<input type="text" onChange={this.onChange.bind(this)}/>
<QueryRenderer
environment={environment}
query={query}
variables={{
accountId: this.state.accountId,
}}
render={({ error, props }) => {
if (error) {
return (
<center>Error</center>
);
} else if (props) {
const { userWithAccount } = props.viewer;
console.log(userWithAccount)
return (
<ul>
{
userWithAccount.map(({name}) => (<li>{name}</li>))
}
</ul>
);
}
return (
<div>Loading</div>
);
}}
/>
</div>
);
}
}
Okay so my last answer didn't work as intended, so I thought I would create an entirely new example to demonstrate what I am talking about. Simply, the goal here is to have a child component within a parent component that only re-renders when it receives NEW props. Note, I have made use of the component lifecycle method shouldComponentUpdate() to prevent the Child component from re-rendering unless there is a change to the prop. Hope this helps with your problem.
class Child extends React.Component {
shouldComponentUpdate(nextProps) {
if (nextProps.id === this.props.id) {
return false
} else {
return true
}
}
componentDidUpdate() {
console.log("Child component updated")
}
render() {
return (
<div>
{`Current child ID prop: ${this.props.id}`}
</div>
)
}
}
class Parent extends React.Component {
constructor(props) {
super(props)
this.state = {
id: 14,
text: 15
}
}
onChange = (event) => {
this.setState({ text: event.target.value })
}
onClick = () => {
this.setState({ id: this.state.text })
}
render() {
return (
<div>
<input type='text' onChange={this.onChange} />
<button onClick={this.onClick}>Change ID</button>
<Child id={this.state.id} />
</div>
)
}
}
function App() {
return (
<div className="App">
<Parent />
</div>
);
}

Why can't update a state when use onKeyPress [duplicate]

This question already has answers here:
How to handle the `onKeyPress` event in ReactJS?
(12 answers)
Closed 4 years ago.
Please considering this follow code, I can't update inputVal when I using a Keypress event handler.
import React, { Component, Fragment } from 'react';
import List from './List';
import './ListTodos.css';
class Todos extends Component {
constructor(props) {
super(props);
this.state = {
inputVal: null
}
this.refInput = null
this._handleChange = this._handleChange.bind(this)
}
_handleChange(pEvt) {
if (pEvt.keyCode === "13") {
this.setState({
inputVal: this.refInput.value
})
console.log(this.state.refInput)
}
}
render() {
const { text } = this.props;
return (
<Fragment>
<div className="form">
<input ref={input => {this.refInput = input}} onKeyDown={pEvt => this._handleChange(pEvt)} className="form__input" placeholder={ text } />
<div>
<List TxtVal={this.state.inputVal} />
</div>
</div>
</Fragment>
)
}
}
export default Todos;
I really dont like using on onKeyDown. Instead you can use onChange which i think its better.
So Basically you need can do this too.
class Todos extends Component {
constructor(props) {
super(props);
this.state = {
inputVal: null
}
this._handleChange = this._handleChange.bind(this)
}
_handleChange(e) {
if (e.keyCode === "13") {
this.setState({
inputVal: e.target.value
})
console.log(e.target.value)
}
}
render() {
const { text } = this.props;
return (
<Fragment>
<div className="form">
<input name="todo" onChange={(e) => this._handleChange(e)} className="form__input" placeholder={ text } />
<div>
<List TxtVal={this.state.inputVal} />
</div>
</div>
</Fragment>
)
}
}
export default Todos;
Use pEvt.target.value instead of this.refInput.value
_handleChange(pEvt) {
if (pEvt.keyCode === "13") {
this.setState({
inputVal: pEvt.target.value
});
console.log(this.state.inputVal);
}
}
You're actually using the KeyDown event in your code instead of KeyPress as you asserted. It looks like you're just trying to get the value of the input element right?
I'd create a handler for the onchange event instead for the input. You're just trying to get the value of the input. And you wouldn't even need your ref.
_handleChange(e) {
this.setState({
inputVal: e.target.value
});
}
constructor() {
// wire up your event handler
this._handleChange = this._handleChange.bind(this);
}
...
<input onChange={this._handleChange} className="form__input" placeholder={ text } />

Categories