I'm trying to create a React component that receive props that contains attribute message. The component renders text 'Too long' if the length of message value is greater than 10. Otherwise the message value is rendered.
my App.js code:
import React from 'react';
import './App.css';
function App(props) {
return (
<div className="App">
{props.message}
</div>
);
}
export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App message="Hello World"/>
</React.StrictMode>,
document.getElementById('root')
);
This is how the app should work: https://imgur.com/a/1LaQitZ I am not sure how to proceed.
CodePudding user response:
I would do this:
import React from 'react';
import './App.css';
function App(props) {
return (
<div className="App">
{props.message.length > 10 ? 'Too long' : props.message}
</div>
);
}
export default App;
Just use a ternary operator to conditionally render either the props.message
value or the string 'Too long'
if it's length is greater than 10.
CodePudding user response:
So you can do this thing in two ways
- Using If else
<div className="App">
{
if(props.message.length > 10){
return "Too Long"
}else{
return props.message
}
}
</div>
- Using the ternary operator
{props.message.length > 10 ? 'Too Long': props.message}