Reputation: 666
Please consider the following:
export default class MyComponent extends React.Component {
constructor() {
super();
this.handleText1Change = this.handleText1Change.bind(this);
this.handleText2Change = this.handleText2Change.bind(this);
this.state = {
text1 : '',
text2 : '',
text3 : `Type something into one of the text fields`
}
}
handleText1Change = (e) => {
e.preventDefault();
this.setState({text1: e.target.value})
}
handleText2Change = (e) => {
e.preventDefault();
this.setState({text2: e.target.value})
}
render() {
return(
<div>
<div class="d-flex flex-row bd-highlight mb-3">
<div class="p-2 bd-highlight">
<label for="text1-box"><h4>Text1</h4></label><br />
<textarea
type="text"
value={this.state.text1}
onChange={this.handleText1Change} />
</div>
<div class="p-2 bd-highlight">
<label for="text2-box"><h4>Text2</h4></label><br />
<textarea
type="text"
value={this.state.text2}
onChange={this.handleText2Change} />
</div>
<div class="p-2 bd-highlight">
<label for="result"><h4>Combined Result</h4></label>
<br />
<p>{this.state.text1 ?
this.state.text1 :
this.state.text2 ?
this.state.text2 :
this.state.text1 && this.state.text2 ?
this.state.text1 + this.state.text2 :
this.state.text3 }</p>
</div>
</div>
</div>
)
}
}
Tho I can display dynamic text if typing into Text1's or Text2's textarea, it appears unable to combine the dynamic text per the condition this.state.text1 && this.state.text2
.
I want to type any text into BOTH textarea boxes and get the combined text this.state.text1 + this.state.text2
(as specified in my ternary statement).
But it's not working and it only seems to be rendering OR but not AND.
How can I make it dynamically render concatenated dynamic text? Is this possible?
To be more clear, if I type 'apple' into the first textarea and 'banana' into the second textarea, I want it to display 'applebanana' but it's not doing so and it only gives 'apple' or 'banana' and fails to render 'applebanana' in Combined Result.
Upvotes: 0
Views: 922
Reputation: 37755
Problem with your code is order of conditions, You will never reach to the this.state.text1 && this.state.text2
condition if any of this.state.text1 or this.state.text2
is true because you have these condition this.state.text1
or this.state.text2
before this.state.text1 && this.state.text2
, you need to get &&
condition before these,
Also don't use nested ternary it is really uneasy for eyes, use a function and inside function use simple if else conditions and call that function in jsx
function giveMeText(state) {
if(state.text1 && state.text2){
return state.text1 + state.text2
}
// so on
}
call the function inside JSX like this
<div> giveMeText(this.state) </div>
Upvotes: 1