1

This is my code:

<Input
      onChange={(e) => someChange(e)}
      valid={check.length !== 0}
      invalid={check.length === 0}
      type="text"
      name="name"
      id="name"
      placeholder={something}
      value={props.someProp ? props.user.name : ''}
/>

So what happens here is when I enter into props.someProp my value gets retrieved. The problem is that I cannot edit that field. Please note that user object gets populated when this screen appears.

How can I make some kind of sanity check so I still get the value populated, but I can edit it afterwards?

Thanks.

5
  • 3
    You cannot dynamically change props - you'll have to store those within state. Also can you provide the code for someChange Commented Jul 24, 2019 at 16:57
  • 1
    what does someChange do? maybe if you inverse the logic like value={ props.user.name? '' : props.someProp} ? Commented Jul 24, 2019 at 16:58
  • someChange basically gets e.target.value and stores it. Commented Jul 24, 2019 at 16:59
  • You also don't necessarily need valid AND invalid since one boolean will be the inverse of the other one Commented Jul 24, 2019 at 17:07
  • @MisterMister "and stores it" where? A parent component? The state of this component? There is not enough information in your question to get the correct answer, please include the entire parent component where <Input /> is being used, as well as any functions referenced. Commented Jul 24, 2019 at 17:39

2 Answers 2

1

If you're using stateless components AND React 16.8+, use hooks. This will allow your stateless component to contain state. React calls these function components.

You might have previously known these as “stateless components”. We’re now introducing the ability to use React state from these, so we prefer the name “function components”.

Example

const Foo = props => {
  const [name, someChange] = useState(props.someProp ? props.user.name : '');

  return (
    <Input
      onChange={(e) => someChange(e.target.value)}
      value={name}
      ...
    />
  );
}

Documentation on hooks can be found here.

Sign up to request clarification or add additional context in comments.

Comments

0

Set the initial state on component mount. After that the inputed value will be set on onChange.

constructor(props){
  super(props);
  this.state({name:''});
}

componentDidMount(){
  this.setState({name: props.someProp ? props.user.name : ''});
}

someChange(e){
 let name = e.target.name;
 this.setState({[name]: e.target.value});
}

<Input
  onChange={(e) => someChange(e)}
  valid={check.length !== 0}
  invalid={check.length === 0}
  type="text"
  name="name"
  id="name"
  placeholder={something}
  value={this.state.name}
/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.