I want to use the new feature on React v16.0.0 for returning a string, then use that string in
<img src="returnedString" >
What is the current behavior?
Well if I render my component in a
<div > <MyComponent /> </div>
I can see the string displayed on the screen (see attached screenshot), but my goal is to use that string in <img src="returnedString" />
here is my code:
// My component that returns strings
class MyComponent extends Component {
render(){
switch (this.props.type) {
case 'text':
return this.props.json.data[this.props.Key]
break
case 'image':
return this.props.json.data[this.props.Key]
break
default:
return null
break
}
}
}
const UserComponent = (props) => {
return (
<div>
{/* this displays the string on the page */}
<MyComponent type='image' Key='avatar' desc='Abified image' {...props} />
{/* If I console.log this line I get <img src={[object object]} /> */}
<img src={<MyComponent type='image' Key='avatar' desc='Abified image' {...props} />} />
</div>
)
}
// Parent Component
class App extends Component {
constructor(props){
super(props)
this.state = {
json:[]
}
}
// Fetching data from an api
componentDidMount(){
fetch("https://reqres.in/api/users/2")
.then(response => response.json())
.then(json => {
this.setState({json: json })
})
}
render() {
return (
<div>
<UserComponent {...this.state}/>
</div>
);
}
}
export default App;
How Can I achieve that?
What is the expected behavior?
I want to use the returned string inside an
Which versions of React ?
React v16.0.0
Did this work in previous versions of React?
No because it's a new feature in React v16.0.0